-2

Given a date like April 22, 2022 how can we accurately determine which Friday of that Month it is. In this case it is the 4th Friday.

I have tried all combinations of adding the week day (0-6, so 5) plus the current day, dividing things by 7, using % because it seems cool, etc. At this point I am stumped.

I am using the Luxon library, but also have access to native JS and dayjs

1 Answers1

2

Try this out:

function getFriday(day, month, year){
    
    date = new Date(year, month - 1, day)

    if (date.getDay() === 5){
        return Math.ceil(day / 7)
    } else{
        return "Date is not a Friday"
    }
}

console.log(getFriday(21, 1, 2022)) // 3
console.log(getFriday(4, 2, 2022)) // 1
console.log(getFriday(22, 4, 2022)) // 4
console.log(getFriday(15, 5, 2022)) // Date is not a Friday

It creates a date object from the function arguments, checks if the date is a Friday, then calculates which Friday it is. If the date is not a Friday, it returns "Date is not a Friday", though this could be removed to return null.

Ben
  • 403
  • 4
  • 16
  • 1
    `Math.floor(((day - 1) / 7) + 1)` is simpler as `Math.ceil(day/7)`. :-) – RobG Apr 19 '22 at 01:40
  • @RobG Indeed, you're right! I threw this together rather quickly and didn't notice that. I'll edit the code with your version :) – Ben Apr 19 '22 at 02:07