[SalesForce] Apex: How to generate List of all Friday Dates for given month

I am trying to create a List of date type which contains every Friday of the month in it. So for example, for the month of March, the list would contain the dates of March 3rd, 10th, 17th, 24th and 31st. Is there any standard function that would calculate this for me? Or perhaps a standard object that I could query which is simply a calendar so I could use the date query functions? I am not looking for something like

DAY_IN_WEEK(CreatedDate) = 6

In which it would get every friday from a query, but simply a list of Fridays for that month regardless of querying an object.

Best Answer

While the other approaches listed here work, they are dependent on locale. I would prefer an approach that will work for anyone, anywhere, which you can do by comparing the month start to a known Sunday. For example:

static Date knownSunday = Date.newInstance(2017, 1, 1);
public static List<Date> getFridays(Integer year, Integer month)
{
    Date monthStart = Date.newInstance(year, month, 1);
    Integer daysAfterSunday = Math.mod(knownSunday.daysBetween(monthStart), 7);
    Date firstFriday = monthStart.addDays(5 - daysAfterSunday);
    if (firstFriday < monthStart)
        firstFriday = firstFriday.addDays(7);

    Datetime pointer = Datetime.newInstance(firstFriday, Time.newInstance(0,0,0,0));
    List<Date> fridays = new List<Date>();
    while (pointer.month() == month)
    {
        fridays.add(pointer.date());
        pointer = pointer.addDays(7);
    }
    return fridays;
}

You can test it out in Execute Anonymous with values for this year:

for (Integer month = 1; month < 13; month++)
    system.debug(JSON.serialize(getFridays(2017, month)));

["2017-01-06","2017-01-13","2017-01-20","2017-01-27"]

["2017-02-03","2017-02-10","2017-02-17","2017-02-24"]

["2017-03-03","2017-03-10","2017-03-17","2017-03-24","2017-03-31"]

["2017-04-07","2017-04-14","2017-04-21","2017-04-28"]

["2017-05-05","2017-05-12","2017-05-19","2017-05-26"]

["2017-06-02","2017-06-09","2017-06-16","2017-06-23","2017-06-30"]

["2017-07-07","2017-07-14","2017-07-21","2017-07-28"]

["2017-08-04","2017-08-11","2017-08-18","2017-08-25"]

["2017-09-01","2017-09-08","2017-09-15","2017-09-22","2017-09-29"]

["2017-10-06","2017-10-13","2017-10-20","2017-10-27"]

["2017-11-03","2017-11-09","2017-11-16","2017-11-23","2017-11-30"]

["2017-12-01","2017-12-08","2017-12-15","2017-12-22","2017-12-29"]

Related Topic