Member-only story
Keeping track of dates and times in software can be complicated. Different parts of the world use different calendar systems, time zones vary, and daylight saving time adds additional complexity.
The ISO 8601 standard provides a universal system for tracking dates that aims to alleviate some of these issues. Part of this standard defines a week numbering system that numbers each week of the year from 1 to 53. This post will walk through how to implement ISO week number calculations in Dart.
Here are the rules for ISO week numbers:
- Week 1 is the week with the year’s first Thursday in it
- All days in a new year prior to that are in week 53 or 52 of the previous year
- Week 1 starts on a Monday and ends on a Sunday
Here is a Dart extension that adds an `weekOfYear` getter to `DateTime` to calculate the ISO week number:
extension DateTimeExtension on DateTime {
int get weekOfYear {
final startOfYear = DateTime(year, 1, 1);
final weekNumber =
((difference(startOfYear).inDays + startOfYear.weekday) / 7).ceil();
return weekNumber;
}
}
This works as follows:
- addCustCreate a `DateTime` for the first day of the year using `DateTime(year, 1, 1)`