Skip to content

Instantly share code, notes, and snippets.

@wshaddix
Created February 4, 2014 03:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save wshaddix/8797934 to your computer and use it in GitHub Desktop.
Save wshaddix/8797934 to your computer and use it in GitHub Desktop.
Gets the week number for a given date
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 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()}");
}
@floitsch
Copy link

floitsch commented Feb 4, 2014

Pay attention that this won't work with daylight-savings.
Edit: The weekNumber is probably correct, but thisMonday or thisThursday could yield bad results.

You can rewrite thisThursday.millisecondsSinceEpoch - firstThursday.millisecondsSinceEpoch using thisThursday.difference(firstThursday)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment