I need to get day of year (day1 is 1rst of january), week of year, and month of year from a dart DateTime object.
I did not find any available library for this. Any idea ?
Fast dependency-free extension methods to get the ISO 8601 week of year from a dart DateTime object. import 'package:week_of_year/week_of_year. dart'; void main() { final date = DateTime. now(); print(date.
[ORIGINAL ANSWER - Please scroll below to the updated answer, which has an updated calculation]
Week of year:
/// Calculates week number from a date as per https://en.wikipedia.org/wiki/ISO_week_date#Calculation int weekNumber(DateTime date) { int dayOfYear = int.parse(DateFormat("D").format(date)); return ((dayOfYear - date.weekday + 10) / 7).floor(); }
The rest is available through DateFormat (part of the intl package).
[UPDATED ANSWER] As pointed out by Henrik Kirk in a comment, the original answer did not include the necessary correction for certain dates. Here is a full implementation of the ISO week date calculation.
/// Calculates number of weeks for a given year as per https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year int numOfWeeks(int year) { DateTime dec28 = DateTime(year, 12, 28); int dayOfDec28 = int.parse(DateFormat("D").format(dec28)); return ((dayOfDec28 - dec28.weekday + 10) / 7).floor(); } /// Calculates week number from a date as per https://en.wikipedia.org/wiki/ISO_week_date#Calculation int weekNumber(DateTime date) { int dayOfYear = int.parse(DateFormat("D").format(date)); int woy = ((dayOfYear - date.weekday + 10) / 7).floor(); if (woy < 1) { woy = numOfWeeks(date.year - 1); } else if (woy > numOfWeeks(date.year)) { woy = 1; } return woy; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With