Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gabotronix's avatar

Get remaining days,hours,minutes seconds to date with date-fns

I want to get remaining full countdown of next instance of weekday (for example next thursday), I have two functions:

FIRST: gets instance of next thursday

SECOND: calculates remaining days,hours,minutes and seconds

I first tried with moment.js but minutes and secodns always return 59 no matter what, days and hours seem to work.

So since moment is deprecated I need to do this wth date-fns which I don't know much about.

Please help me!

let nextThursday = getNextThursday();
        console.log('nextThursday',nextThursday);
LOG nextThursday "2022-03-22T14:30:31.514Z
        getCountdown(nextThursday);
 LOG Days:  2
 LOG  Hours:  23
 LOG  Minutes:  59
 LOG  Seconds:  59


const getCountdown = (ending) => {
    var now = moment();
    var end = moment(ending); // another date
    var duration = moment.duration(end.diff(now));
    
    console.log(end.diff(now))
  
    //Get Days and subtract from duration
    var days = duration.days();
    duration.subtract(days, 'days');
  
    //Get hours and subtract from duration
    var hours = duration.hours();
    duration.subtract(hours, 'hours');
  
    //Get Minutes and subtract from duration
    var minutes = duration.minutes();
    duration.subtract(minutes, 'minutes');
  
    //Get seconds
    var seconds = duration.seconds();
    console.log("Days: ", days);
    console.log("Hours: ", hours);
    console.log("Minutes: ", minutes);
    console.log("Seconds: ", seconds);
  };
 LOG  Minutes:  59
 LOG  Seconds:  59
const getNextThursday = () => {
        const dayINeed = 4; // for thursday
        const today = moment().isoWeekday();

        // if we haven't yet passed the day of the week that I need:
        if (today <= dayINeed) { 
        // then just give me this week's instance of that day
           return moment().isoWeekday(dayINeed);
        } else {
         // otherwise, give me *next week's* instance of that same day
           return moment().add(1, 'weeks').isoWeekday(dayINeed).utcOffset(0).set({hour:0,minute:0,second:0,millisecond:0});
           //return moment().add(1, 'weeks').add(22, 'minutes').add(43, 'seconds').isoWeekday(dayINeed);
        }
};
0 likes
2 replies
tykus's avatar

Was there somnething wrong with the answer I gave you three days ago @gabotronix ?

import { intervalToDuration, nextThursday, startOfToday } from "date-fns";
let duration = intervalToDuration({
  start: new Date(),
  end: nextThursday(startOfToday())
})

You don't need separate getCountdown and getNextThursday functions - date-fns takes care of those implementation details

Please or to participate in this conversation.