[SalesForce] SOQL query to find every Friday of month

Am a trying to find a way to query every Friday of a month passed in to my apex controller. So say we're looking at March, I want my query to return data from the 3rd, 10th, 17th, 24th and 31st. I see that there is a

DAY_IN_MONTH()

function, but this returns the number in that month and not the day itself. Is there an easy way to do this?

Follow up question: How could I create a list of Dates with the passed in month's Fridays. So this would have either 4 or 5 elements each call. I am making a Lightning cmp table header and would like the headers to be the 4 -5 friday days for the selected month but am finding this difficult.

Best Answer

As far as how that function can be used in a query, it would look something lie:

SELECT Id FROM MyObject__c WHERE CreatedDate = THIS_MONTH
AND DAY_IN_MONTH(CreatedDate) IN (3, 10, 17, 24, 31)

However, you could instead use DAY_IN_WEEK and save yourself the trouble of calculating which dates you need:

WHERE DAY_IN_WEEK(CreatedDate) = 6

Note that 1 represents Sunday, and 7 represents Saturday. Since Saturday - 1 = Friday, you should use a value of 6

If you wanted to query records created on Fridays in a particular month/year, it would look like:

public static List<MyObject__c> getRecordsCreatedFriday(Integer year, Integer month)
{
    return [
        SELECT ... FROM MyObject__c
        WHERE CALENDAR_YEAR(CreatedDate) = :year
        AND CALENDAR_MONTH(CreatedDate) = :month
        AND DAY_IN_WEEK(CreatedDate) = 6
    ];
}

You could also add an overload that accepts just a date within the month to filter:

public static List<MyObject__c> getRecordsCreatedFriday(Date dateInMonth)
{
    return getRecordsCreatedFriday(dateInMonth.year(), dateInMonth.month());
}

It might just be worth reading up on all Date Functions.