Skip to content

Instantly share code, notes, and snippets.

@Maksclub
Last active November 20, 2023 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maksclub/3dbe8cdf6f17ae42f4aaf251772cfb83 to your computer and use it in GitHub Desktop.
Save Maksclub/3dbe8cdf6f17ae42f4aaf251772cfb83 to your computer and use it in GitHub Desktop.
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
export function formatPlayerTime(ms: number, options?: {withHour?: boolean}) {
if (ms <= 0) {
if (!!options?.withHour) {
return '00:00:00';
}
return '00:00';
}
const hour = Math.floor(ms / HOUR);
ms = ms % HOUR;
const minute = Math.floor(ms / MINUTE);
ms = ms % MINUTE;
const secondWithMs = ms / SECOND;
const second = Math.floor(secondWithMs);
if (hour || !!options?.withHour) {
return `${padZero(hour)}:${padZero(minute)}:${padZero(second)}`;
}
return `${padZero(minute)}:${padZero(second)}`;
}
function padZero(num: number, len = 2): string {
let str = String(num);
const threshold = Math.pow(10, len - 1);
if (num < threshold) {
while (String(threshold).length > str.length) {
str = `0${num}`;
}
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment