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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With