Skip to content

Instantly share code, notes, and snippets.

@z4vmk
Last active October 9, 2024 03:22
Show Gist options
  • Save z4vmk/2e36e9980b6d45d7eecf071c0c2322b0 to your computer and use it in GitHub Desktop.
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').
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