Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last midnight in Dart?

Tags:

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?

like image 367
Marek Lisý Avatar asked Jul 09 '18 16:07

Marek Lisý


People also ask

How do you find the next date in darts?

var nextDate = new Date(new Date(). getTime() + 24 * 60 * 60 * 1000); var day = nextDate. getDate() var month = nextDate. getMonth() + 1 var year = nextDate.

How do you subtract time in darts?

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.


2 Answers

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.

like image 174
Günter Zöchbauer Avatar answered Sep 18 '22 01:09

Günter Zöchbauer


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 
like image 45
Jama Mohamed Avatar answered Sep 19 '22 01:09

Jama Mohamed