Search code examples
javascriptdate-fns

Date-fns: Countdown to a specific date


I'm using date-fns. I need to create a countdown to the next 10th of the month.

For example, if today is 5th Feb, then the countdown should be to 10th Feb. If today is say 15th Feb, then it should count to 10th March, and so on.

How can I do this with date-fns or even with plain javascript?


Solution

  • You must first find the target date, like this one:

    const today = startOfToday();
    let target = setDate(today, 10);
    if (isBefore(target, today)) {
      target = addMonths(target, 1);
    }
    

    Then calculate time remaining until the target:

    const diff = differenceInSeconds(target, new Date());
    const days = Math.floor(diff / 86400);
    const hours = Math.floor((diff - days * 86400) / 3600);
    const minutes = Math.floor((diff - days * 86400 - hours * 3600) / 60);
    const seconds = diff - days * 86400 - hours * 3600 - minutes * 60;
    

    Use days, hours, minutes, seconds for create a countdown. Don't forget to import required functions from date-fns.