Cris - 2 years ago 120
Javascript Question

# moment.js get hh:mm:ss from a decimal nr

From the value 126.55 (126 mins, 55 seconds) how can i get an output like 02:06:55

``````var d = moment.duration(126.55,'minutes');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
var secs = Math.floor(d.asSeconds()) - mins * 60;
console.log(hours + ":" + mins + ":" + secs);
``````

My output is 2:6:7233

Desired output 02:06:55

I suggest to use moment-duration-format plugin, but, before all, the number of seconds must be converted from seconds to decimal (i.e.: 55 seconds are 91 hundredths of a second):

``````window.onload = function() {
var min = 6.55;
min =  parseInt(min)+ (min * 100 % 100) / 60;
var result = moment.duration(min ,'minutes').format("HH:mm:ss", {trim: false});
document.getElementById('log').textContent = result;
}``````
``````<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

<p id="log"></p>``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download