Skip to content

Instantly share code, notes, and snippets.

@Matsukii
Last active January 23, 2022 16:45
Show Gist options
  • Select an option

  • Save Matsukii/96c989bbe90283a9eaded28b34bae13f to your computer and use it in GitHub Desktop.

Select an option

Save Matsukii/96c989bbe90283a9eaded28b34bae13f to your computer and use it in GitHub Desktop.
Convertion from HH:MM:SS to seconds - inspired by this answer https://stackoverflow.com/a/9640417
/**
* @description convert hms string to seconds
* @see performance test with jsBench: https://jsbench.me/rckgfk8iv7
* @license MIT
*
* @param {String} str HH:MM:SS
* @example str = '01:00:10' return 3610
* @returns {Number} time as seconds
*/
const hmsToSeconds = (str) => {
str = str.split(':').reverse();
let m = [1, 60, 3600];
let sec = 0;
for(t in str){
sec += (+str[t]) * m[t]
}
return sec
}
@Matsukii
Copy link
Author

Its made to be able to use anything like:

hmsToSenconds('01:00:10')
hmsToSenconds('00:10')
hmsToSenconds('10')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment