0

I have a startTime and endTime based on which I need to create a countdown which will display in HH:MM:SS format at all times.

For example:

var endTime = 1601454312537 // Wed Sep 30 2020 13:55:12 
var startTime = 1600417512537 // Fri Sep 18 2020 13:55:12 
var diff = endTime - startTime
var duration = moment.duration(diffTime * 1000, 'milliseconds')

The difference is then passed to setInterval where,

setInterval(() => {
    duration = moment.duration(duration - interval, 'milliseconds');
    h = duration.hours(),
    m = duration.minutes(),
    s = duration.seconds() 
}, 1000);

This gives me correct time but when it exceeds 24 hrs, moment passes it in a day. Is there any way I can keep it all the diff in HH:MM:SS format? Is there any moment function to restrict it to hours, min, sec?

Magiczne
  • 1,586
  • 2
  • 15
  • 23

2 Answers2

0

This is one function that I use that does not require momentjs, there is no direct way to do this in momentjs either:

// Duration in seconds
const durationString = duration =>
  `${
    Math.floor(duration / 60) > 9 ? Math.floor(duration / 60) : `0${Math.floor(duration / 60)}`
  } m ${duration % 60 > 9 ? Math.round(duration % 60) : `0${Math.round(duration % 60)}`}s`
Trisma
  • 735
  • 6
  • 19
0

Posting the solution which worked for me -
You can further split the minutesSeconds string.

var minutesSeconds = moment.utc(totalMilliseconds).format("mm:ss")
var hours = Math.floor(moment.duration(totalMilliseconds).asHours())
console.log("HH:MM:SS",hours + ':' + minutesSeconds)