isoWeekOfYear method

int isoWeekOfYear()

Calculates the ISO 8601 week number of the year for the current DateTime instance.

The ISO 8601 standard defines weeks as starting on Monday, with Week 1 being the week containing the first Thursday of the year.

Example Usage:

final date = DateTime(2025, 2, 5);
print(date.isoWeekOfYear()); // Output: 6 (Feb 5th falls in the 6th ISO week of 2025)

Returns:

  • An integer representing the ISO 8601 week number of the year.

How It Works:

  1. Adjusts the current date to the nearest Thursday (since ISO weeks are based on Thursdays).
  2. Determines the start of the year.
  3. Calculates the difference in days and divides by 7 to find the week number.

Note:

  • ISO weeks start on Monday.
  • Week 1 is the week containing the first Thursday of the year.

Implementation

int isoWeekOfYear() {
  // Adjust to the nearest Thursday (ISO weeks are based on Thursdays)
  final thursdayOfCurrentWeek = this.subtract(Duration(days: weekday - 4));

  // Get the first day of the year
  final startOfYear = DateTime(thursdayOfCurrentWeek.year, 1, 1);

  // Compute days since the start of the year and divide by 7
  final daysSinceStart = thursdayOfCurrentWeek.difference(startOfYear).inDays;

  return (daysSinceStart / 7).floor() + 1;
}