Skip to content

Instantly share code, notes, and snippets.

@jozsefs
Last active March 16, 2018 09:21
Show Gist options
  • Save jozsefs/688fc3db6b903c6bc0566cb9f222deea to your computer and use it in GitHub Desktop.
Save jozsefs/688fc3db6b903c6bc0566cb9f222deea to your computer and use it in GitHub Desktop.
formatDuration.js
const LABELS = ['year', 'day', 'hour', 'minute', 'second'];
function formatDuration (seconds) {
if (seconds === 0) return 'now';
let minutes = seconds / 60 >> 0;
let hours = minutes > 59 ? minutes / 60 >> 0 : 0;
let days = hours > 23 ? hours / 24 >> 0 : 0;
const years = days > 364 ? days / 365 >> 0 : 0
if (seconds > 59) seconds = seconds % 60;
if (minutes > 59) minutes = minutes % 60;
if (hours > 23) hours = hours % 24;
if (days > 364) days = days % 365;
return [years, days, hours, minutes, seconds]
.map((item, idx) => item && (item > 1 ? item + ' ' + LABELS[idx] + 's' : item + ' ' + LABELS[idx]))
.filter(item => item) // filter out zeroes
.join(', ')
.replace(/(^.+)([,])(.+$)/, '$1 and$3') // replace the "something, something" part at the end
}
const Test = {
assertEquals(a, b) {
if (a !== b) throw new Error(`Expected: ${b} but instead got: ${a}`);
console.log(`Test passed: ${b}`);
}
};
Test.assertEquals(formatDuration(1), "1 second");
Test.assertEquals(formatDuration(62), "1 minute and 2 seconds");
Test.assertEquals(formatDuration(120), "2 minutes");
Test.assertEquals(formatDuration(3600), "1 hour");
Test.assertEquals(formatDuration(3662), "1 hour, 1 minute and 2 seconds");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment