简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM