Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to convert a decimal time (e.g. 1.074 minutes) into mm:ss format using moment.js?

I was wondering if there's a simple way, using moment.js library, to transform a decimal time interval (for example, 1.074 minutes) into its equivalent 'mm:ss' value. I am currently using a function which doesn't work too well with negative times (it outputs the value in '-m:ss' format):

function secTommss(sec){
 var min = Math.floor(sec/60)
 sec = Math.round(Math.abs(sec) % 60);
 return min + ":" + (sec < 10 ? "0" + sec : sec)
}
like image 676
JAC Avatar asked Jul 11 '13 16:07

JAC


People also ask

How do you convert decimal minutes to minutes and seconds?

When a time is expressed as a decimal that includes hours, the hours remain the same upon conversion. Multiply the remaining decimal by 60 to determine the minutes. If that equation produces a decimal number, multiply the decimal by 60 to produce the seconds.


1 Answers

Here is some JavaScript that will do what you are asking:

function minTommss(minutes){
 var sign = minutes < 0 ? "-" : "";
 var min = Math.floor(Math.abs(minutes));
 var sec = Math.floor((Math.abs(minutes) * 60) % 60);
 return sign + (min < 10 ? "0" : "") + min + ":" + (sec < 10 ? "0" : "") + sec;
}

Examples:

minTommss(3.5)        // "03:30"
minTommss(-3.5)       // "-03:30"
minTommss(36.125)     // "36:07"
minTommss(-9999.999)  // "-9999:59"

You could use moment.js durations, such as

moment.duration(1.234, 'minutes')

But currently, there's no clean way to format a duration in mm:ss like you asked, so you'd be re-doing most of that work anyway.

like image 169
Matt Johnson-Pint Avatar answered Oct 25 '22 02:10

Matt Johnson-Pint