Snappawapa
Snappawapa

Reputation: 2012

Moment.js getting duration from now until future date

I am trying to implement a countdown timer by getting each part of the time until the event (minutes, seconds, etc), with support for timezones. I cannot seem to figure out how to get Moment.js to get the duration between now and a future dated Moment object.

Here is what I have tried:

var eventStartDatetime = moment.parseZone('2022 07 02 13 -05:00', 'YYYY MM DD HH ZZ')
var monthsNum = $("#monthsNum");
var daysNum = $("#daysNum");
var hoursNum = $("#hoursNum");
var minutesNum = $("#minutesNum");
var secondsNum = $("#secondsNum");

console.log(eventStartDatetime.toString())

function updateCountdown(){
    // get difference between user's time (and zone) and the event time
    var difference = moment.duration(eventStartDatetime, 'seconds');
    
    monthsNum.text(difference.months());
    daysNum.text(difference.days());
    hoursNum.text(difference.hours());
    minutesNum.text(difference.minutes());
    secondsNum.text(difference.seconds());
}
updateCountdown();

window.setInterval(function(){
    console.log("Doing repeated update.");
    updateCountdown();
}, 5000);

I have verified that the eventStartDateTime is correct, as the log statement matches what is put in. However, the moment.duration() call seems to give back the incorrect duration, and never has a value for minutes or seconds.

I'm sure I am close, but am missing some detail. I am also having trouble making heads or tails of the Moment documentation.

Upvotes: 0

Views: 955

Answers (1)

Ishmam
Ishmam

Reputation: 53

You can use the toNow() method.

Upvotes: 1

Related Questions