我需要从 dart DateTime 对象获取一年中的某一天(day1 是 1 月 1 日)、一年中的星期和月份。
我没有找到任何可用的库。有什么想法吗?
最佳答案
[原始答案 - 请滚动到下面的更新答案,其中包含更新的计算]
一年中的第几周:
/// 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();
}
其余可通过DateFormat获取(intl package 的一部分)。
[更新的答案] 正如 Henrik Kirk 在评论中指出的那样,最初的答案没有包括对某些日期的必要更正。这是 ISO 周日期计算的完整实现。
/// 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;
}
关于datetime - 如何从 DateTime Dart 对象获取一年中的某一天、一年中的第几周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49393231/