How to find the last day of the month?

I'm trying to use the new Google Dart language, and I don’t know how to get the last day of the current month?

This gives me the current date:

var now = new DateTime.now();
+5
source share
2 answers

Providing a daily zero value for the next month gives the previous month in the last month

var date = new DateTime(2013,3,0);
print(date.day);  // 28 for February
+10
source

Here is one way to find it:

var now = new DateTime.now();

// Find the last day of the month.
var beginningNextMonth = (now.month < 12) ? new DateTime(now.year, now.month + 1, 1) : new DateTime(now.year + 1, 1, 1);
var lastDay = beginningNextMonth.subtract(new Duration(days: 1)).day;

print(lastDay); // 28 for February

I have the current date, so I create the first day of the next month, and then subtract one day from it. I also take into account the change in the year.

Update: Here's a slightly shorter code for the same thing, but inspired by Chris zero-trick:

var now = new DateTime.now();

// Find the last day of the month.
var lastDayDateTime = (now.month < 12) ? new DateTime(now.year, now.month + 1, 0) : new DateTime(now.year + 1, 1, 0);

print(lastDayDateTime.day); // 28 for February

/, (, ).

+4

All Articles