Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ void main() {
- `isAfterOrEqual`: Checks if the current DateTime is after or equal to the given DateTime
- `isBeforeOrEqual`: Checks if the current DateTime is before or equal to the given DateTime
- `isBetween`: Checks if the current DateTime is between the given dates
- `calendarWeek`: calculates the calendar week number of the current DateTime object.

Example:

Expand Down
39 changes: 39 additions & 0 deletions lib/extensions/date_time.extension.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,43 @@ extension DateTimeExtension on DateTime {
final isBefore = isBeforeOrEqual(toDateTime);
return isAfter && isBefore;
}

///
/// Returns the calendar week of the year for this date.
///
int calendarWeek() {
// Add 3 to always compare with January 4th, which is always in week 1
// Add 7 to index weeks starting with 1 instead of 0
final weekOfYear = ((ordinalDate - weekday + 10) ~/ 7);

// If the week number equals zero, it means that the given date belongs to the preceding (week-based) year.
if (weekOfYear == 0) {
// The 28th of December is always in the last week of the year
return DateTime(year - 1, 12, 28).calendarWeek();
}

// If the week number equals 53, one must check that the date is not actually in week 1 of the following year
if (weekOfYear == 53 &&
DateTime(year, 1, 1).weekday != DateTime.thursday &&
DateTime(year, 12, 31).weekday != DateTime.thursday) {
return 1;
}

return weekOfYear;
}

/// The ordinal date, the number of days since December 31st the previous year.
///
/// January 1st has the ordinal date 1
///
/// December 31st has the ordinal date 365, or 366 in leap years
int get ordinalDate {
const offsets = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
return offsets[month - 1] + day + (isLeapYear && month > 2 ? 1 : 0);
}

/// True if this date is on a leap year.
bool get isLeapYear {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
}
Loading