22

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Arief Wijaya
  • 827
  • 2
  • 8
  • 20

9 Answers9

45

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 10
    If you only want the month, I recommend using `DateTime(date.year, date.month - 1, 1)`. If you use `date.day` you risk overflowing for, say, March 31st. There is no obvious answer to "which day is one month before March 31st", and different use-cases will want different answers (but 3rd of March is usually not what anybody wants :smile:). To get the *last* day of the previous month, use `DateTime(date.year, date.month, 0)`. – lrn Jul 20 '18 at 09:58
  • nice explanation. I'll use it – Arief Wijaya Jul 20 '18 at 10:33
  • 1
    How we can get last date of current month? – Pankaj Bansal Jul 02 '19 at 11:56
  • 2
    Create a Date for the first day of the next month and subtract a day. – Günter Zöchbauer Jul 02 '19 at 12:13
14

We can calculate both first day of the month and the last day of the month:

DateTime firstDayCurrentMonth = DateTime.utc(DateTime.now().year, DateTime.now().month, 1);

DateTime lastDayCurrentMonth = DateTime.utc(DateTime.now().year, DateTime.now().month + 1).subtract(Duration(days: 1));

DateTime.utc takes in integer values as parameters: int year, int month, int day and so on.

Oded Ben Dov
  • 9,936
  • 6
  • 38
  • 53
Ashutosh Ojha
  • 151
  • 1
  • 4
9

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);
Jama Mohamed
  • 3,057
  • 4
  • 29
  • 43
  • Thanks for the solution. I am using this code: String lastMonth = Jiffy(date).subtract(months: 1).MMMM; – md-siam Dec 31 '22 at 07:27
6

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

DateTime pastMonth = DateTime.now().subtract(Duration(days: 30));
Alwin
  • 1,476
  • 3
  • 19
  • 35
  • 8
    That wouldn't work on the 31st of any given month...Also in February it could go back two months. – Hasen Oct 13 '19 at 05:22
  • `DateTime createdAt = Timestamp.now().toDate(); createdAt.subtract(Duration(days: 7)); print("createdAt: $createdAt");` Not worked for me. Printing current timestamp, not seven 7 days earlier datetime . Kindly suggest. Thanks. – Kamlesh Aug 11 '21 at 06:34
2

Dates are pretty hard to calculate. There is an open proposal to add support for adding years and months here https://github.com/dart-lang/sdk/issues/27245.

There is a semantic problem with adding months and years in that "a month" and "a year" isn't a specific amount of time. Years vary by one day, months by up to three days. Adding "one month" to the 30th of January is ambiguous. We can do it, we just have to pick some arbitrary day between the 27th of February and the 2nd of March. That's why we haven't added month and year to Duration - they do not describe durations.

You can use the below code to add months in a arbitrary fashion (I presume its not completely accurate. Taken from the issue)

const _daysInMonth = const [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

bool isLeapYear(int value) =>
    value % 400 == 0 || (value % 4 == 0 && value % 100 != 0);

int daysInMonth(int year, int month) {
  var result = _daysInMonth[month];
  if (month == 2 && isLeapYear(year)) result++;
  return result;
}

DateTime addMonths(DateTime dt, int value) {
  var r = value % 12;
  var q = (value - r) ~/ 12;
  var newYear = dt.year + q;
  var newMonth = dt.month + r;
  if (newMonth > 12) {
    newYear++;
    newMonth -= 12;
  }
  var newDay = min(dt.day, daysInMonth(newYear, newMonth));
  if (dt.isUtc) {
    return new DateTime.utc(
        newYear,
        newMonth,
        newDay,
        dt.hour,
        dt.minute,
        dt.second,
        dt.millisecond,
        dt.microsecond);
  } else {
    return new DateTime(
        newYear,
        newMonth,
        newDay,
        dt.hour,
        dt.minute,
        dt.second,
        dt.millisecond,
        dt.microsecond);
  }
}
Arif Amirani
  • 26,265
  • 3
  • 33
  • 30
0

To get a set starting point at the start of a month, you can use DateTime along with the Jiffy package.

DateTime firstOfPreviousMonth 
  = DateTime.parse(
      Jiffy().startOf(Units.MONTH)
           .subtract(months: 1)
           .format('yyyy-MM-dd'). //--> Jan 1 '2021-01-01 00:00:00.000'
  );  

var fifthOfMonth 
  = firstOfPreviousMonth.add(Duration(days: 4)); //--> Jan 5 '2021-01-05 00:00:00.000'

or

DateTime endOfPreviousMonth 
  = DateTime.parse(
      Jiffy().endOf(Units.MONTH)
           .subtract(months: 2)
           .format('yyyy-MM-dd'). //--> Dec 30 '2020-12-31 00:00:00.000' 
                                  // endOf always goes to 30th
  );  

var previousMonth 
      = endOfPreviousMonth.add(Duration(days: 2)); //--> Jan 1 '2021-01-01 00:00:00.000'
aabiro
  • 3,842
  • 2
  • 23
  • 36
0

DateFormat('MMMM yyyy') .format(DateTime(DateTime.now().year, DateTime.now().month - 2)),

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 08 '22 at 20:06
0
 List<DateTime> newList = [];
 DateFormat format = DateFormat("yyyy-MM-dd");
    for (var i = 0; i < recents.length; i++) {
  newList.add(format.parse(recents[i]['date'].toString()));
}
newList.sort(((a, b) => a.compareTo(b)));
var total = 0;
for (var i = 0; i < newList.length; i++) {
if (DateTime.now().difference(newList[i]).inDays < 30) {
print(newList[i]);
total++;
}
}
print(total);

You can use this to fetch the last 30 days.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 28 '22 at 11:02
-3

In addition to Günter Zöchbauer Answer

var now = new DateTime.now();
    String g = ('${now.year}/ ${now.month}/ ${now.day}');
    print(g);
SilenceCodder
  • 2,874
  • 24
  • 28