I guess this is pretty common task in most languages, however it was not clear to me how to get this done in my Flutter app. How to retrieve DateTime object of the last midnight in Dart? Or potentially, any particular time today / tomorrow / yesterday?
var nextDate = new Date(new Date(). getTime() + 24 * 60 * 60 * 1000); var day = nextDate. getDate() var month = nextDate. getMonth() + 1 var year = nextDate.
subtract methodDateTime today = new DateTime. now(); DateTime fiftyDaysAgo = today. subtract(new Duration(days: 50)); Notice that the duration being subtracted is actually 50 * 24 * 60 * 60 seconds.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With