Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Last Month Date In Flutter / Dart

in flutter we can get current month using this

var now = new DateTime.now();
var formatter = new DateFormat('MM');
String month = formatter.format(now);

But how to get the last month date? Especially if current date is January (01). we can't get the right month when we use operand minus (-) , like month - 1.

like image 770
Arief Wijaya Avatar asked Jul 19 '18 10:07

Arief Wijaya


People also ask

How do I get the last date of the month in Flutter?

How to get the Last Day of a month in Dart and Flutter. Construct the DateTime object using the constructor with month always considered as value -1. For example, Object using DateTime(2013, 3, 0); created with Feb 2013 data.

How do I get the past date in Flutter?

How to select previous or next dates based on the selected date in the Flutter Date Range Picker (SfDateRangePicker) In the Flutter Date Range Picker, you can highlight the before and after date ranges of the selected date by using onSelectionChanged callback of the Flutter date range picker.

How do you add months to a date in Flutter?

To add 6 Months. DateTime d = Jiffy(). add(months: 6); // 2020-04-26 10:05:57.469367 // You can also add you own Datetime object DateTime d = Jiffy(DateTime(2018, 1, 13)). add(months: 6);


1 Answers

You can just use

var prevMonth = new DateTime(date.year, date.month - 1, date.day);

with

var date = new DateTime(2018, 1, 13);

you get

2017-12-13

It's usually a good idea to convert to UTC and then back to local date/time before doing date calculations to avoid issues with daylight saving and time zones.

like image 52
Günter Zöchbauer Avatar answered Oct 11 '22 11:10

Günter Zöchbauer