[SalesForce] How to get the last monday of every month

i need to get the list of last monday of every month between two dates.

i have startdate and enddate.

List<Date> dates= new List<Date>;

while(enddate >= startdate)

{

//logic

}

i am unable to understand what logic i should put to get last monday.

Best Answer

You just need to do some back-and-forth calculation to end up where you want.

while(enddate >= startdate) {
    // Remember current month
    Integer currentMonth = startDate.month();
    startDate = startDate
        .toStartOfMonth()   // First day of current month
        .addMonths(1)       // First day of next month
        .addDays(-1)        // Last day of current month
        .toStartOfWeek()    // Go to last Sunday of the current month
        .addDays(1);        // Last Monday of the current month
    // If last day of month was Sunday, go back a week
    if(startDate.month() != currentMonth) {
        startDate = startDate.addDays(-7);
    }
    // Still a valid date
    if(endDate >= startDate) {
        dates.add(startDate);
    }
    // Move forward to next month
    startDate = startDate.toStartOfMonth().addMonths(1);
}

N.B. This answer assumes that toStartOfWeek returns Sunday, which is not true for all locales. If you need to be concerned about international users, you'll have to determine if the locale starts on Sunday or Monday, which will determine if you need the addDays(1) at the end of the calculation.

Related Topic