Home > Software engineering >  Moment.js padd 0 if haven't hours or minutes
Moment.js padd 0 if haven't hours or minutes

Time:10-10

I have this code to transform seconds to time

let secs = 5323795;
let duration = moment.duration(Number(secs), "seconds");
let formatted = duration.format("hh:mm:ss");
formatted; // '1.478:49:55' 

but, if seconfs is less than 1min, the result is

let secs = 35;
let duration = moment.duration(Number(secs), "seconds");
let formatted = duration.format("hh:mm:ss");
formatted; // '35' 

// CORRECT OUTPUT: "00:00:35"

How i fix that?

CodePudding user response:

You can use the trim option in moment duration format to keep all fields, setting trim to false will accomplish this:

let secs = 35;
let duration = moment.duration(Number(secs), "seconds");
let formatted = duration.format("hh:mm:ss", { trim: false });

console.log('Formatted:', formatted)
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.3.2/moment-duration-format.min.js" integrity="sha512-ej3mVbjyGQoZGS3JkES4ewdpjD8UBxHRGW MN5j7lg3aGQ0k170sFCj5QJVCFghZRCio7DEmyi 8/HAwmwWWiA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  • Related