Skip to content

Instantly share code, notes, and snippets.

@jr-k
Last active May 23, 2019 16:31
Show Gist options
  • Save jr-k/5a1e27884e6b6cc2a30f3d8caefef8ee to your computer and use it in GitHub Desktop.
Save jr-k/5a1e27884e6b6cc2a30f3d8caefef8ee to your computer and use it in GitHub Desktop.
Convert seconds to display date in HH:MM:SS format
const secondsToHHMMSS = function(opts) {
const sec = opts.seconds;
const hrs = Math.floor(sec / 3600);
const min = Math.floor((sec - (hrs * 3600)) / 60);
let seconds = sec - (hrs * 3600) - (min * 60);
seconds = Math.round(seconds * 100) / 100;
let result = opts.hideHourIfZero && hrs == 0 ? '' : ((opts.leadingZeroHour && hrs < 10 ? "0" + hrs : hrs) + opts.minuteToSecondsSeparator);
result += hrs == 0 && opts.hideMinuteIfZero && min == 0 ? '' : (( (opts.leadingZeroMinute && min < 10) && !(hrs == 0 && opts.noLeadingZeroMinuteIfHeader) ? "0" + min : min) + opts.hourToMinuteSeparator);
result += hrs == 0 && min == 0 && opts.hideSecondIfZero && seconds == 0 ? '' : (( (opts.leadingZeroSeconds && seconds < 10) && !(hrs == 0 && min == 0 && opts.noLeadingZeroSecondIfHeader) ? "0" + seconds : seconds)) + (opts.secondToVoidSeparator);
return result;
};
const tests = [0, 5, 10, 59, 60, 69, 123, 3599, 3600, 3601, 86399, 86400, 89000, 232320]
for (let i = 0; i < tests.length; i++) {
console.log(secondsToHHMMSS({
seconds: tests[i],
hideHourIfZero: true,
hideMinuteIfZero: false,
hideSecondIfZero: false,
minuteToSecondsSeparator: ':',
hourToMinuteSeparator: ':',
secondToVoidSeparator: '',
leadingZeroHour: true,
leadingZeroMinute: true,
leadingZeroSeconds: true,
noLeadingZeroMinuteIfHeader: false,
noLeadingZeroSecondIfHeader: false
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment