简体   繁体   English

如何在flutter中仅给出年份​​中的日期来获取日期

[英]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.在 android 中,我可以轻松地使用cal.set(Calendar.DAY_OF_YEAR, number)设置的Calendarcal.set(Calendar.DAY_OF_YEAR, number)它将返回该特定day_of_year数字的date How can I do the same in Flutter.我如何在 Flutter 中做同样的事情。

In Android, this is what I would have done在 Android 中,这就是我会做的

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.我如何在 Flutter 中实现这一点。

I gave this a go for fun, I don't normally do Dart, so apologies if its wrong!我只是为了好玩,我通常不做 Dart,所以如果它错了,请道歉!

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.对于一年中的一天 == 1。
  • When there are 86400000 milliseconds in a day.当一天有 86400000 毫秒时。
  • Then there are 86400000 millis in that year (1 x 86400000).那一年有 86400000 毫秒(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 https://api.dart.dev/stable/2.7.1/dart-core/DateTime-class.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从字符串日期获取日,月,年? - How to get day,month,year from String date? 如何获取给定日期的工作日以在Android Studio中使用日历 - how to get week day for given date for using Calendar in android studio 如何仅从日期选择器获取日期的月份和年份 - How to Get date from Date Picker only month and year 从一年中的天数中获取日期名称 android - get day name from day number of the year android 如何更改日期的json字符串并将其格式化为仅显示不带年,月,日或时间的日期 - How to change json string of date and format it to only show the day without, year, month, or time 如何获取给定日期与上一个记录日期之间的天数? - How to get the number of days between a given date and the previous records date? 如何从日,月,年,小时和分钟获取13位(时期)的日期和时间? - How to get date & time in 13 digit(epoch time) from day,month,year,hours and minutes? 如何从Android中的日期选择器获取DAY_OF_YEAR? - How do I get the DAY_OF_YEAR from a Date Picker in Android? 如何从Android中选定的日期月份和年份中获取星期几名称? - How to get day of week name from selected date month and year in Android? Android Java - 如何在DatePicker中获取一年中的某一天? - Android Java - how to get day of year in DatePicker?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM