Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get day of year, week of year from a DateTime Dart object

Tags:

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 ?

like image 368
fvisticot Avatar asked Mar 20 '18 20:03

fvisticot


People also ask

How do you get the week of the year in Flutter?

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.


1 Answers

[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; } 
like image 141
András Szepesházi Avatar answered Dec 07 '22 22:12

András Szepesházi