=EOMONTH(A2, -1) - returns the last day of the month, one month before the date in cell A2.
Subtract Dates in Excel To find the number of dates between the start date and end date, use this formula in cell C2: =B2-A2.
Providing a day value of zero for the next month gives you the previous month's last day
var date = new DateTime(2013,3,0);
print(date.day); // 28 for February
Try this in an easy way:
DateTime now = DateTime.now();
int lastday = DateTime(now.year, now.month + 1, 0).day;
Here's 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 construct the first day of the next month, and then subtract one day out of it. I'm also taking the change of the year into account.
Update: Here's a little bit shorter code for the same thing, but inspired by Chris's 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
It has the additional check/code, in case you want to do this programmatically (e.g. you have a specific month as an integer).
Another way is using Jiffy. It has the endOf method that makes easy to get the last moment of several units, in this case the month:
Jiffy().endOf(Units.MONTH);
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