11 dart
我正在尝试新的Google Dart语言,我不知道如何获得当月的最新一天?
这给了我当前的日期:
var now = new DateTime.now();
Run Code Online (Sandbox Code Playgroud)
Chr*_*ett 32
在下个月提供零日值会为您提供上个月的最后一天
var date = new DateTime(2013,3,0);
print(date.day); // 28 for February
Run Code Online (Sandbox Code Playgroud)
小智 22
以简单的方式尝试此操作:
DateTime now = DateTime.now();
int lastday = DateTime(now.year, now.month + 1, 0).day;
Run Code Online (Sandbox Code Playgroud)
这是找到它的一种方法:
var now = new DateTime.now();
// Find the last day of the month.
var beginningNextMonth = (now.month < 12) ? new DateTime(now.year, now.month + 1, 1) : new DateTime(now.year + 1, 1, 1);
var lastDay = beginningNextMonth.subtract(new Duration(days: 1)).day;
print(lastDay); // 28 for February
Run Code Online (Sandbox Code Playgroud)
我有当前日期,所以我构建了下个月的第一天,然后从中减去一天.我也考虑到了今年的变化.
更新:对于同样的事情,这里有一些更短的代码,但灵感来自Chris的零技巧:
var now = new DateTime.now();
// Find the last day of the month.
var lastDayDateTime = (now.month < 12) ? new DateTime(now.year, now.month + 1, 0) : new DateTime(now.year + 1, 1, 0);
print(lastDayDateTime.day); // 28 for February
Run Code Online (Sandbox Code Playgroud)
它有额外的检查/代码,以防您想以编程方式执行此操作(例如,您将特定月份作为整数).
小智 9
这是一个可能有帮助的扩展。(参考 Kai 和 Chris 的回答。)
extension DateTimeExtension on DateTime {
DateTime get firstDayOfWeek => subtract(Duration(days: weekday - 1));
DateTime get lastDayOfWeek =>
add(Duration(days: DateTime.daysPerWeek - weekday));
DateTime get lastDayOfMonth =>
month < 12 ? DateTime(year, month + 1, 0) : DateTime(year + 1, 1, 0);
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用Jiffy。它有endOf方法,可以轻松获取几个单位的最后时刻,在本例中是月份:
Jiffy.now().endOf(Unit.month);
// Or if you have an existing Datetime
Datetime dt = DateTime.now();
Jiffy.parseFromDateTime(dt).endOf(Unit.month);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3335 次 |
| 最近记录: |