Get Last Month Date In Flutter / Dart

2020-03-24 05:24发布

问题:

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.

回答1:

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.



回答2:

We can use the subtract method to get past month date.

DateTime pastMonth = DateTime.now().subtract(Duration(days: 30));


回答3:

Try this package, Jiffy, it used momentjs syntax. See below

Jiffy().subtract(months: 1);

Where Jiffy() returns date now. You can also do the following, the same result

var now = DateTime.now();
Jiffy(now).subtract(months: 1);

Jiffy respects the leap years and how many days there are in each month



回答4:

In addition to Günter Zöchbauer Answer

var now = new DateTime.now();
    String g = ('${now.year}/ ${now.month}/ ${now.day}');
    print(g);