Is there a cleaner way of getting the last day of the previous month?
Also, is the Date.addMonth()
function smart enough to deal with months having different numbers of days? As in, if I subtract 1 month from October 31st, do I get Sept 31st or Sept 30th?
//Get Last Day or previous month.
Date LastMonth = date.today().addmonths(-1);
Date FirstOfLastMonth = date.newInstance(Lastmonth.year(), lastmonth.month(), 1);
Integer numberOfDays = Date.daysInMonth(FirstOfLastMonth.year(), FirstOfLastMonth.month());
Date LastDayOfLastMonth = Date.newInstance(FirstOfLastMonth.year(), FirstOfLastMonth.month(), numberOfDays);
newInstance
also adds the days to the month. i.e.date.newInstance(2016,02,31)
created a date of 3/2/2016 instead of throwing an error. For kicks I used 132 and got a date in july iirc – Eric Sep 9 '16 at 23:35