Last active
September 9, 2017 10:07
-
-
Save tegola/0baac8b7515fd2cf0133f3c7c58bdbc6 to your computer and use it in GitHub Desktop.
Convert a string in decimal or clock format in hh:mm format using moment.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert a string in decimal or clock format in hh:mm format using moment.js | |
* Examples: | |
* 1.5 > 1:30 | |
* 1,4 > 1:24 | |
* 2:70 > 3:10 | |
* | |
* @param string time | |
* @return string | |
*/ | |
function timeToClockFormat(time) { | |
let seconds = 0; | |
if (time.includes(':')) { | |
// Clock style to seconds conversion | |
const timeArray = time.split(':'); | |
seconds = moment.duration({ | |
hours: timeArray[0], | |
minutes: timeArray[1] | |
}).asSeconds(); | |
} else { | |
// Number to seconds conversion | |
let multiplier = parseFloat(time.replace(',', '.')); | |
if (isNaN(multiplier)) multiplier = 0; | |
seconds = 3600 * multiplier; | |
} | |
// Round to minutes | |
seconds = Math.round(seconds / 60) * 60; | |
return seconds; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment