我需要从dart DateTime对象中获取一年中的第几天(day1是1月1日)、一年中的第几周和第几个月。
我没有找到任何可用的库。有什么想法吗?
发布于 2019-01-10 21:00:26
原始答案-请滚动到下面的更新答案,其中包含更新的计算
一年中的星期:
/// 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;
}发布于 2018-03-21 13:57:02
一年中的某天
final date = someDate;
final diff = now.difference(new DateTime(date.year, 1, 1, 0, 0));
final diffInDays = diff.inDays;一年中的星期
final date = someDate;
final startOfYear = new DateTime(date.year, 1, 1, 0, 0);
final firstMonday = startOfYear.weekday;
final daysInFirstWeek = 8 - firstMonday;
final diff = date.difference(startOfYear);
var weeks = ((diff.inDays - daysInFirstWeek) / 7).ceil();
// It might differ how you want to treat the first week
if(daysInFirstWeek > 3) {
weeks += 1;
}一年中的月份
final monthOfYear = new DateTime.now().month;注意:这不是经过战斗测试的代码。
发布于 2019-10-22 18:19:02
试试这个非常简单的dart包,Jiffy。下面的代码将会有所帮助
要获取日期,请执行以下操作
// This will return the day of year from now
Jiffy().dayOfYear; // 295
// You can also pass in a dateTime object
Jiffy(DateTime(2019, 1, 3)).dayOfYear; // 3以获得一年中的星期
Jiffy().week; // 43
// You can also pass in an Array or Map
Jiffy([2019, 1, 3]).week; // 1获取一年中的月份
Jiffy().month; // 10
Jiffy({
"year": 2019,
"month": 1,
"day": 3
}).month; // 1希望这个答案能有所帮助
https://stackoverflow.com/questions/49393231
复制相似问题