Getting the Last Day of the Month from a Date

The Apex Date class does not have a method to determine the last day of the month. You can obtain the last day of the month by adding and subtracting dates as follows:

// Get the last day of the month for a given date
private date lastDayOfMonth(Date d){
    Date nextMonthStartDate = d.addMonths(1).toStartOfMonth();
    return nextMonthStartDate.addDays(-1);
}

system.debug(lastDayOfMonth(Date.newInstance(2024,4,5))); // 2024-4-30

The lastDayOfMonth method finds the last day of the month for the given date in the following steps:

  1. Use addMonths(1) to get the date one month after the given date. In the sample, it gets May 5, 2024, from April 5, 2024.
  2. Use the toStartOfMonth() method of the Date class to get the first day of that month. In the sample, it gets May 1, 2024, as the first day of May 2024.
  3. Finally, use addDays(-1) to get the day before. In the sample, it gets April 30, 2024, as the day before May 1, 2024.