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

Is there a function or method to give the last day of a month?
For example
if the date is 27 feb 2013, the last date should be 28 feb 2013 , it become 29 if its a leap year. if the date was 2 jan then it should return 31 Jan.

If there is no function then any ideas on how we can get this?

Thanks

Best Answer

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.

Related Topic