1

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

Cristian Muscalu
  • 9,007
  • 12
  • 44
  • 76
  • 1
    have a look here http://stackoverflow.com/questions/13262621/how-do-i-use-format-on-a-moment-js-duration and here http://momentjs.com/docs/ (you are searching for `format()` method – messerbill May 20 '16 at 14:24
  • Check out this plugin: https://github.com/jsmreese/moment-duration-format. I think this is what you're looking for – Duncan Lukkenaer May 20 '16 at 14:54

2 Answers2

1

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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • Thanks! Your solution works fine, except for when i do a filter. If the value get's smaller (less then an hour) it looses the format. For ex instead of 00:06:55 i get 06:55. U know how i can persist the hh:mm:ss format even on small values? – Cristian Muscalu May 23 '16 at 06:10
  • @Cris Snippet updated. Use trim to force the leading value when it's 0. For details see https://github.com/jsmreese/moment-duration-format/blob/master/README.md Let me know.. – gaetanoM May 23 '16 at 08:54
0

Try this:

var value = 126.55;

var minutes = Math.floor(value),
    seconds = (value - minutes) * 100;

var duration = moment.duration(minutes, 'minutes').add(seconds, 'seconds');

alert(moment.utc(duration.asMilliseconds()).format("HH:mm:ss"));
<script src="http://momentjs.com/downloads/moment.js"></script>
Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97