How to get last midnight in Dart?

Try this package Jiffy, uses the simplicity of momentjs syntax. See below

To get last midnight

var lastMidnight = Jiffy().subtract(days: 1).startOf(Units.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

EDIT: Use this solution only if you are working with UTC (daylight saving times might mess it up), or rather use the accepted answer anyway.


The simplest solution I found so far:

final now = DateTime.now();
final lastMidnight = now.subtract(Duration(
  hours: now.hour,
  minutes: now.minute,
  seconds: now.second,
  milliseconds: now.millisecond,
  microseconds: now.microsecond,
));

Then we can get any other time or day relative to today by subtracting or adding Duration, e.g.:

final tomorrowNoon = lastMidnight.add(Duration(days: 1, hours: 12));
final yesterdaySixThirty = lastMidnight
    .subtract(Duration(days: 1))
    .add(Duration(hours: 6, minutes: 30));

Note that DateTime is immutable and both methods (add, subtract) return a new object.


This should do the same

var now = DateTime.now();
var lastMidnight = DateTime(now.year, now.month, now.day);

You can use this way to get different times of this day

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

var yesterdaySixThirty = DateTime(now.year, now.month, now.day - 1, 6, 30);

Depending on what you want can absolute values be more safe because adding/subtracting Duration can result in surprises because of leap years and daylight saving time.