Last active
October 9, 2024 03:22
-
-
Save z4vmk/2e36e9980b6d45d7eecf071c0c2322b0 to your computer and use it in GitHub Desktop.
Converts a given number of seconds into a human-readable format of days, hours, minutes, and seconds (e.g., '2d 10h 30m 15s').
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 formatTime(seconds: number): string { | |
if (seconds <= 0) return '0s'; | |
const units: [number, string][] = [ | |
[86400, 'd'], | |
[3600, 'h'], | |
[60, 'm'], | |
[1, 's'] | |
]; | |
let result = ''; | |
for (const [divisor, suffix] of units) { | |
if (seconds >= divisor) { | |
const value = Math.floor(seconds / divisor); | |
result += `${value}${suffix} `; | |
seconds %= divisor; | |
} | |
} | |
return result.trim(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment