怎么在Dart最后一个午夜?

Mar*_*isý 7 datetime dart flutter

我想这在大多数语言中都是非常常见的任务,但是我不清楚如何在我的Flutter应用程序中完成此操作.如何在Dart中检索最后一个午夜的DateTime对象?或者可能,今天/明天/昨天的任何特定时间?

Gün*_*uer 15

这应该做同样的事情

final now = DateTime.now();
final lastMidnight = new DateTime(now.year, now.month, now.day);
Run Code Online (Sandbox Code Playgroud)

你可以用这种方式来获得今天的不同时间

final tomorrowNoon = new DateTime(now.year, now.month, now.day + 1, 12);

final yesterdaySixThirty = new DateTime(now.year, now.month, now.day - 1, 6, 30);
Run Code Online (Sandbox Code Playgroud)

根据您的需要,绝对值可以更安全,因为添加/减少Duration会因闰年和夏令时而导致意外.


Jam*_*med 5

尝试这个包Jiffy ,使用momentjs语法的简单性。见下文

为了得到最后一个午夜

var lastMidnight = Jiffy.now().subtract(days: 1).startOf(Unit.day);

print(lastMidnight.dateTime); // 2019-10-20 00:00:00.000
//or you can also format it
print(lastMidnight.yMMMMEEEEdjm); // Sunday, October 20, 2019 12:00 AM
Run Code Online (Sandbox Code Playgroud)