How do we get the last day of the month from a given date

You can also use:

yourDate.addMonths(1).toStartofMonth().addDays(-1). 

This will give you the last day of current month. What this basically does is it adds 1 month to current date and then use the toStartofMonth() to take you to the 1ST day of next month. Finally we are subtracting 1 day from the 1st day of next month which will give you the last day of current month.


Check out salesforce documentation on their Date class.

The method you are looking for is daysInMonth(...)

Integer numberOfDays = Date.daysInMonth(dateField.year(), dateField.month());
Date lastDayOfMonth = Date.newInstance(dateField.year(), dateField.month(), numberOfDays);

Keep in mind "dateField" above is a place holder for any Date variable or field you want to go off.

Tags:

Apex