15

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

23

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.

37

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.

  • 2
    I was initially concerned with how yourDate.addMonths(1) will handle 1/31, but it appears safe. It returns the exact date from the next month, and if next month is shorter, it returns the last day of next month. So, for 1/31, it will return 2/28 or 2/29. – geeljire Jun 21 '14 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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