mivd
mivd

Reputation: 389

Format amount of seconds to minutes and seconds with momentjs

I'd like to use momentjs to use a given amount of seconds (e.g. 65) and format that to minutes and seconds (so in the case of 65 seconds it should format it to '01:05'). I've looked around the momentjs docs and also here but I couldn't quite get to the right solution. I know there's a way to do this with just pure JavaScript, but I'd like to use momentjs for this. Any suggestions?

Upvotes: 0

Views: 693

Answers (1)

Titus
Titus

Reputation: 22474

If you insist on doing this using moment.js, you can do something like this: Start with a 00:00:00.000 time and add seconds, minutes, etc. to it. Here is an example:

const result = moment("00:00:00.000", "hh:mm:ss.SSS").add(65, "s").format("mm:ss");
console.log(result);
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>

The problem is that since this is the time of a date, when you add 24 hours to it, you'll end up with 00:00:00 instead of 24:00:00.

Upvotes: 1

Related Questions