How can I calculate yesterdays date in dart/flutter? I have the date of today:
DateTime.now()
But I can't just do -1.
Simply use the methods isAfter() , isBefore() or isAtSameMomentAs() from DateTime . Other alternative, use compareTo(DateTime other) , as in the docs: Compares this DateTime object to [other], returning zero if the values are equal. Returns a negative value if this DateTime [isBefore] [other].
var nextDate = new Date(new Date(). getTime() + 24 * 60 * 60 * 1000); var day = nextDate. getDate() var month = nextDate.
You can format date and time in different combinations mixed with year, day, weekday, month, month name, hour, minute, second, and many more. First, add, intl Flutter package in your project by adding the following lines in pubspec.yaml file. How to format date and time using the intl Flutter package. DateFormat () is from intl package.
We check whether day, month and year of the current DateTime subtracted by a day equal the respective values of the given DateTime and return Yesterday, followed by the rough time string we stored above if the condition evaluates to true.
Let’s implement a date formatter that puts out a string in the above mentioned way. We start by implementing a new class called DateFormatter with a single public method getVerboseDateTimeRepresentation. We let it expect a UTC DateTime as its purpose is to receive a DateTime and return a string.
DateTime.now().subtract(Duration(days:1))
More info at https://api.flutter.dev/flutter/dart-core/DateTime-class.html
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