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

Gabotronix's avatar

Date countown timer: minutes and seconds alwyas 59 with moment.js

Hi everybody, in my app I want to get next instance of friday at 00:00, I get a timestamp like this:

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


Notice the timestamp doesnt have 00:00 in it, that's why I think remaning minutes adn seconds are always 59.

The function to get the remaining days,hours,minutes and seconds is this one:

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

While days and hours seem fine minutes and seconds always return 59:

 LOG  Minutes:  59
 LOG  Seconds:  59

My function for getting next instance of specified day is this:

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

I know moment is deprecated , if you know a way to get this working using data-fns I would love to see it

0 likes
1 reply
tykus's avatar

If I am understanding you correctly; you can achieve all of this using:

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

Please or to participate in this conversation.