Search code examples
javascriptdate-fns

Date-fns: Get Countdown to a specific UTC time on a specific day or date


I'm using date-fns library. And I have a specific requirement.

Let's say I have an event every Saturday at 7am UTC.

  1. If there are 24 hours left in the event, I want to say 'Coming Soon'. If more than 24 hours are left, I want to show the calendar days targeting 7am UTC of the next Saturday.

  2. As soon, as it is past 7am UTC of the Saturday, it should show calendar days left to next Saturday 7am UTC.

I'm not sure how I can achieve this.

If it was to check Saturday irrespective of time, I could just use isSaturday(), but that's not the case, I need to target the specific UTC time on the next Saturday (7am UTC).

UPDATE: The main problem I'm facing is to define the target as the next Saturday 7am UTC. Once the target is defined, then I can use differenceInCalendarDays() to get the days left.

Can you please help?


Solution

  • To answer the "main problem" is quite simple without using date-fns - it may be simpler using date-fns but I don't know date-fns - so here is plain ol' javascript Date object solution

    function nextSaturday(d = new Date) {
        const next = new Date(d);
        next.setUTCDate(next.getUTCDate() + (7 - (next.getUTCDay() + 1)) % 7);
        next.setUTCHours(7, 0, 0, 0);
        if (next <= d) { // if it's currently saturday after 7AM UTC, add 7 days
            next.setUTCDate(next.getUTCDate() + 7);
        }
        return next;
    }
    console.log(nextSaturday(new Date).toUTCString());
    // for future readers
    // Saturday March 5th 2022 is a Satruday
    // at 06:59:59.999 - next should be Sat, 05 Mar 2022 07:00:00 GMT
    console.log(nextSaturday(new Date('2022-03-05T06:59:59.999Z')).toUTCString());
    // at 07:00:00 - next should be Sat, 05 Mar 2022 07:00:00 GMT
    console.log(nextSaturday(new Date('2022-03-05T07:00:00.000Z')).toUTCString());
    console.log(nextSaturday(new Date('2022-05-15T07:00:00.000Z')).toUTCString());

    Made the function so calling nextSaturday without an argument will use current date - but if you pass in a date it'll use that - this is just for verifying that it works