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);
  • Adrian's already given you an answer, but yes, addMonths is intelligent enough to round down to the last day of the month if it has fewer days than the month you're starting from. – sfdcfox Sep 9 '16 at 21:30
  • @sfdcfox - Something I noticed today if you use a number larger than the number of days in the month 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

You can make it a fair bit more elegant and clear (not to mention one-lining it) by leveraging the Date.toStartOfMonth method.

public static Date getEndOfLastMonth(Date input)
    return input.toStartOfMonth().addDays(-1);
  • Adrian, You are always so helpful! Is Stackexchange post answering your full time job?! :) – Matt M Sep 9 '16 at 19:11
  • 4
    No but it's a useful outlet if I get frustrated by what I'm working on at the moment. I learn a lot from it! I've picked up several techniques in answering posts that a week/month/year later turned out to be very valuable experience. – Adrian Larson Sep 9 '16 at 19:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.