Search code examples
salesforceapex-code

how do we get the first and last day of the current month


How do we get the first day of the month and last day of the month. i am using it on a apex class.

i can get the todays date by using

date.today()

but how would i get the first and last day of the month.

Thanks


Solution

  • You should get familiar with the Apex Code Developers Guide as it has very good documentation for questions like this. Here's the Date methods page that you would find helpful.

    With respect to your specific question, you get the first date of the month (I'll use today's month in my example) using the following

    Date firstDayOfMonth = System.today().toStartOfMonth();

    To get the last day of the month, use the following:

    Date lastDayOfMonth = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);