Add leading zeroes to a moment.js time
Asked Answered
R

4

13

I'm currently using moment.js to handle the displaying of time in a node.js application - is there a way I can ALWAYS have the date formatted with leading zeroes, and atleast two characters wide?

So for 9 days, 1 hour, 12 minutes and 23 seconds

09:01:12:23

or for 1 minute

00:00:01:00

Thanks anyone that can help


I'm calculating the time between two things in a database, and then sending it to moment.js in seconds.

duration.html(difference.add(1, "seconds").format("d:hh:mm:ss"));

Essentially I'd like to enforce that even when days are 0 they be displayed, along with the leading zero for single digit numbers.

Retardment answered 7/12, 2016 at 14:4 Comment(0)
P
18

You can use moment-duration format plug-in:

Use the trim option to show units that have no value. As the docs says:

Leading tokens are automatically trimmed when they have no value. To stop that behavior, set { trim: false }.

Here a working example:

var d1 = moment.duration({
  seconds: 23,
  minutes: 12,
  hours: 1,
  days: 9
});
var d2 = moment.duration({
  minutes: 1
});
console.log(d1.format('DD:HH:mm:ss'));
console.log(d2.format('DD:HH:mm:ss', { trim: false }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
Philipson answered 7/12, 2016 at 14:17 Comment(2)
Note that moment-duration-format is different from momentjs which is why trim doesn't appear anywhere on the momentjs site. Thanks VincenzoC for { trim: false }Barramunda
@Barramunda I know that moment-duration-format is a momentjs plug-in, I've edited my answer to make it clearer. As a side note, there is an open [issue](github.com/moment/moment/issues/1048 to plan duration format integration in moment core). I'm glad my answer helped you :)Philipson
R
2

try moment(your_date, "your_date_format").format("DD:HH:mm:ss");

Rankin answered 7/12, 2016 at 14:9 Comment(3)
That wont work because looking at the question the OP wants the duration not to display the dateHasa
ohh.. I'm confused. You mean, 9 is no of days and not date? right?Rankin
Question was updated ya thats it its not a date just daysHasa
S
0

use format letter double times in format instead of one.

e.g

moment(new Date()).format("DD MMM YY")

will give leading zero, but

moment(new Date()).format("D MMM YY")

won't

Sibling answered 27/3, 2024 at 9:57 Comment(0)
R
-3

Use this:

function addZeros(d,h,m,s){
  return  ("0"+d).substr(-2) + ":" +("0"+h).substr(-2) + ":"+("0"+m).substr(-2) + ":" +("0"+s).substr(-2);
}
Rightward answered 7/12, 2016 at 14:13 Comment(1)
Use this for what?Subkingdom

© 2022 - 2025 — McMap. All rights reserved.