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?
CodePudding user response:
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.
CodePudding user response:
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);
CodePudding user response:
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
CodePudding user response:
final currentDay = DateTime.now();
final yesterday = now.subtract(const Duration(hours: 24));