-
-
Save granoeste/a91cd8e840ca60e5f0b67ad9c408ec1b to your computer and use it in GitHub Desktop.
Gets the week number for a given date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
main () { | |
// get today's date | |
var now = new DateTime.now(); | |
// set it to feb 10th for testing | |
//now = now.add(new Duration(days:7)); | |
int today = now.weekday; | |
// ISO week date weeks start on monday | |
// so correct the day number | |
var dayNr = (today + 6) % 7; | |
// ISO 8601 states that week 1 is the week | |
// with the first thursday of that year. | |
// Set the target date to the thursday in the target week | |
var thisMonday = now.subtract(new Duration(days:(dayNr))); | |
var thisThursday = thisMonday.add(new Duration(days:3)); | |
// Set the target to the first thursday of the year | |
// First set the target to january first | |
var firstThursday = new DateTime(now.year, DateTime.JANUARY, 1); | |
if(firstThursday.weekday != (DateTime.THURSDAY)) | |
{ | |
firstThursday = new DateTime(now.year, DateTime.JANUARY, 1 + ((4 - firstThursday.weekday) + 7) % 7); | |
} | |
// The weeknumber is the number of weeks between the | |
// first thursday of the year and the thursday in the target week | |
//var x = thisThursday.millisecondsSinceEpoch - firstThursday.millisecondsSinceEpoch; | |
var x = thisThursday.difference(firstThursday).inMilliseconds; | |
var weekNumber = x.ceil() / 604800000; // 604800000 = 7 * 24 * 3600 * 1000 | |
print("Todays date: ${now}"); | |
print("Monday of this week: ${thisMonday}"); | |
print("Thursday of this week: ${thisThursday}"); | |
print("First Thursday of this year: ${firstThursday}"); | |
print("This week is week #${weekNumber.ceil()}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment