Skip to content

Instantly share code, notes, and snippets.

@tamboer
Last active December 27, 2015 11:09
Show Gist options
  • Save tamboer/7316306 to your computer and use it in GitHub Desktop.
Save tamboer/7316306 to your computer and use it in GitHub Desktop.
convert decimal to time.js
Ho to transform a decimal time interval (for example, 1.074 minutes) into its equivalent 'mm:ss' value.
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:125"
minTommss(-9999.999) // "-9999:59"
You could use moment.js durations, such as
moment.duration(1.234, 'minutes')
//======================================
//not working well with negative numbers
//======================================
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hours = parseInt(hoursMinutes[0], 10);
var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
//return hours + minutes / 60;
return (hours + minutes / 60).toFixed(2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment