Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

Check out salesforce documentation on their Date class. http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_date.htm

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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