'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 seconds always return 59 no matter what, days and hours seem to work.

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

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);
        }
};


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source