I have a current datetime with followint function :
String cdate = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());
Now I want to subtract 1 day or 24 hours from this current date time.
How can i do that?
I have a current datetime with followint function :
String cdate = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());
Now I want to subtract 1 day or 24 hours from this current date time.
How can i do that?
Don't manipulate the string, manipulate the date. From docs, adapted:
final now = DateTime.now();
final yesterday = now.subtract(const Duration(days: 1));
Apply the formatting just before you need to display the date, not before.
Date manipulation methods are provided by the DateTime class. Refer to DateTime documentation. Checkout now, add, subtract.
The following code shows how you can achieve what you want:
DateTime today = DateTime.now();
String cdate = DateFormat("yyyy-MM-dd HH:mm:ss").format(today);
DateTime yesterday = today.subtract(Duration(days: 1));
String ydate = DateFormat("yyyy-MM-dd HH:mm:ss").format(yesterday);
Try below code also refer add and subtract for DateTime
void main() {
var date = new DateTime.now();
date = DateTime(date.year, date.month, date.day - 1);
// or use subtract method also like below
//final day= date.subtract(Duration(days: 1));
print(date);
print(day);
}
Result using day-1:
2022-09-13 00:00:00.000
Result using subtract method :
2022-09-13 12:52:45.734
final currentDay = DateTime.now();
final yesterday = now.subtract(const Duration(hours: 24));