【发布时间】:2020-01-21 11:04:51
【问题描述】:
如何在 Dart 中以数字形式获取当月的当前周?我需要创建某种带有周视图的日历,上面写着“2. 一月的一周”
【问题讨论】:
-
你找到答案了吗?我现在有同样的问题))
如何在 Dart 中以数字形式获取当月的当前周?我需要创建某种带有周视图的日历,上面写着“2. 一月的一周”
【问题讨论】:
extension DateTimeExtension on DateTime {
int get weekOfMonth {
var wom = 0;
var date = this;
while (date.month == month) {
wom++;
date = date.subtract(const Duration(days: 7));
}
return wom;
}
}
然后像这样使用它:
var wom = DateTime.now().weekOfMonth;
【讨论】:
您可以使用 DateTime().now() 来获取系统的当前时间和日期或今天的日期。下面是sn-p的代码:
// Current date and time of system
String date = DateTime.now().toString();
// This will generate the time and date for first day of month
String firstDay = date.substring(0, 8) + '01' + date.substring(10);
// week day for the first day of the month
int weekDay = DateTime.parse(firstDay).weekday;
DateTime testDate = DateTime.now();
int weekOfMonth;
// If your calender starts from Monday
weekDay--;
weekOfMonth = ((testDate.day + weekDay) / 7).ceil();
print('Week of the month: $weekOfMonth');
weekDay++;
// If your calender starts from sunday
if (weekDay == 7) {
weekDay = 0;
}
weekOfMonth = ((testDate.day + weekDay) / 7).ceil();
print('Week of the month: $weekOfMonth');
或者,如果正在寻找日历月份 UI 的完整实现,那么 click here
【讨论】: