Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created January 12, 2021 14:32
Show Gist options
  • Save bartwttewaall/447d831d7955fc0e276d3dbf7a4ec330 to your computer and use it in GitHub Desktop.
Save bartwttewaall/447d831d7955fc0e276d3dbf7a4ec330 to your computer and use it in GitHub Desktop.
Simple time formatting without the use of Date (expensive)
/**
* @param {Number} time in seconds
**/
export function secondsToObject(time) {
const hours = Math.floor(time / 3600);
const minutes = Math.floor((time - hours * 3600) / 60);
const seconds = Math.floor(time - minutes * 60);
return { hours, minutes, seconds };
}
/**
* @param {Object} timeObject
**/
export function formatTimeObject(timeObject) {
return timeObject.minutes.toString().padStart(2, '0') + ':' + timeObject.seconds.toString().padStart(2, '0');
}
/**
* @param {Number} currentTime in seconds
* @param {Number | String} duration in seconds or a predefined string (since the duration won't change often)
* @returns {String}
**/
export function formatToTimestamps(currentTime, duration) {
const timeString = formatTimeObject(secondsToObject(currentTime));
const durationString = typeof duration === 'string' ? duration : formatTimeObject(secondsToObject(duration));
return timeString + ' / ' + durationString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment