How to get date given only the day of year number in flutter

1,167

I gave this a go for fun, I don't normally do Dart, so apologies if its wrong!

var dayOfYear = 1;
var millisInADay = Duration(days: 1).inMilliseconds; // 86400000    
var millisDayOfYear = dayOfYear * millisInADay;
var millisecondsSinceEpoch = DateTime(DateTime.now().year).millisecondsSinceEpoch;

var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch + millisDayOfYear);
  • For the day of year == 1.
  • When there are 86400000 milliseconds in a day.
  • Then there are 86400000 millis in that year (1 x 86400000).
  • Create a new date for the first day of the year.

  • Add the number of millis in the year, to the number of millis to the start of the year since epoch. Create a new date using this milliseconds since epoch.

Reference:

https://api.dart.dev/stable/2.7.1/dart-core/DateTime-class.html

Share:
1,167
leeCoder
Author by

leeCoder

Leke has been a passionate programmer since he compiled his first hello program in Java. Programming in Java and Android is essentially what l do.

Updated on December 17, 2022

Comments

  • leeCoder
    leeCoder over 1 year

    I am fairly new to flutter. In android, I could easily use the Calendar class set using cal.set(Calendar.DAY_OF_YEAR, number) and it will return the date for that particular day_of_year number. How can I do the same in Flutter.

    In Android, this is what I would have done

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_YEAR,1);  //set date using day of year
    return cal.getTime(); //2020-01-01
    

    How do I implement this in Flutter.

  • leeCoder
    leeCoder about 4 years
    thanks very much, it worked. Interestingly, dayOfYear is 0 for January 1 in Dart. So my first day_of_year is 0. thanks