Last active
March 2, 2022 00:20
-
-
Save isaackogan/34afe4091c21c667efe18fb50c564745 to your computer and use it in GitHub Desktop.
Convert seconds into DD:HH:MM:SS format that automatically removes leading values and does not include leading zeroes in the first non-zero value.
This file contains hidden or 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
function secondsToMilitary(seconds) { | |
let negative = seconds < 0; | |
seconds = Math.abs(Math.floor(seconds)); | |
/* | |
Less than 60 seconds | |
*/ | |
if (seconds < 60) { | |
return "00:" + ((seconds > 10) ? seconds.toString() : '0' + seconds) | |
} | |
/* | |
Find Days, Hours, Minutes, Seconds | |
*/ | |
let DdHhMmSs = [ | |
Math.floor(seconds / 86400), // Days | |
Math.floor(seconds / 3600) % 24, // Hours | |
Math.floor(seconds / 60) % 60, // Minutes | |
seconds % 60 // Seconds | |
]; | |
/* | |
Remove leading zeros | |
*/ | |
DdHhMmSs = DdHhMmSs.filter( | |
// For each entry (Days -> Seconds) | |
(number, index, array) => { | |
// Check if the ones before it including it are zero | |
return !(array.slice(0, index + 1).every((_number) => _number === 0)) | |
} | |
) | |
/* | |
Convert array to timestamp | |
*/ | |
DdHhMmSs = DdHhMmSs.map( | |
(number, index) => { | |
return ( | |
// If the item is bigger than 9 or it's the leading number | |
(number > 9 || index === 0) ? number.toString() : '0' + number | |
) | |
} | |
) | |
// Join with delimiter | |
return (negative ? "-" : "") + DdHhMmSs.join(":"); | |
} | |
/* | |
Uses an anonymous function, will be slower | |
*/ | |
const secondsToMilitaryMini = (s) => (s < 0 ? "-" : '') + ((s) => (s < 60 ? "00:" + ((s > 10) ? s.toString() : '0' + s) : ([Math.floor(s / 86400), Math.floor(s / 3600) % 24, Math.floor(s / 60) % 60, s % 60].filter((number, index, array) => !(array.slice(0, index + 1).every((_number) => _number === 0))).map((number, index) => (number > 9 || index === 0) ? number.toString() : '0' + number).join(":"))))(Math.abs(Math.floor(s))); | |
/* | |
Faster than the one-liner, for values larger than 0. | |
*/ | |
function secondsToTimestamp(s) { | |
s = Math.floor(s); | |
return s < 60 ? "00:" + ((s > 9) ? s.toString() : '0' + s) : ( | |
[Math.floor(s / 86400), Math.floor(s / 3600) % 24, Math.floor(s / 60) % 60, s % 60] | |
.filter((number, index, array) => !(array.slice(0, index + 1).every((_number) => _number === 0))) | |
.map((number, index) => (number > 10 || index === 0) ? number.toString() : '0' + number) | |
.join(":") | |
); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment