2

I'm using moment js to format milliseconds into a mm:ss format with the following code

moment(myVariable).format('mm:ss');

This works perfectly fine, however a requirement for the app I'm building needs to show 60 minutes as 60:00 rather than using hours like 01:00:00. I came across another post that suggested doing

moment.duration(myVariable, 'seconds').asMinutes();

however it formats 3,600,000 milliseconds into minutes as 60000 instead of 60:00. Is there a way to make it display as 60:00?

Optiq
  • 2,835
  • 4
  • 33
  • 68

2 Answers2

1

You can generate string manually:

var d = moment.duration(3600000); // in ms
// slice used for add leading zero
var str = `${d.hours() * 60 + d.minutes()}:${('0' + d.seconds()).slice(-2)}`;
Kirill
  • 161
  • 2
  • 15
  • I think it's not possible to do this via moment.js. You can view this question https://stackoverflow.com/questions/13262621/how-to-use-format-on-a-moment-js-duration – Kirill Apr 25 '23 at 06:35
  • One more thing. When the minutes gets down to less than 10 the minutes are displayed in single digits such as `9:57` and I need it to display as `09:57`. How could I make it do that? – Optiq Apr 26 '23 at 21:24
  • @Optiq you can use example for seconds from my answer or visit https://stackoverflow.com/questions/1267283/how-can-i-pad-a-value-with-leading-zeros – Kirill Apr 27 '23 at 05:35
1

Alternatively, you can consider using .diff method:

const m = moment(myVariable);
`${m.diff(0, 'minutes').padStart(2, '0')}:${m.format('ss')}`;
AngYC
  • 3,051
  • 6
  • 20