Skip to content

Instantly share code, notes, and snippets.

@davelnewton
Last active August 16, 2016 20:46
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 davelnewton/a1371867527c5f1530498e1555e2fb0a to your computer and use it in GitHub Desktop.
Save davelnewton/a1371867527c5f1530498e1555e2fb0a to your computer and use it in GitHub Desktop.
Date Formatting
function pluralize(dur, s) {
var ret = false;
if (dur > 0) {
ret = dur + ' ' + s;
if (dur > 1) {
ret += 's';
}
}
return ret;
}
function formatDuration(seconds) {
var segments = [];
var years = Math.floor(seconds / 31556952)
, sYears = pluralize(years, 'year')
;
if (sYears) {
segments.push(sYears);
}
var days = Math.floor((seconds % 31556952) / 86400)
, sDays = pluralize(days, 'day')
;
if (sDays) {
segments.push(sDays);
}
var hours = Math.floor(((seconds % 31556952) % 86400) / 3600)
, sHours = pluralize(hours, 'hour')
;
if (sHours) {
segments.push(sHours);
}
var minutes = Math.floor((((seconds % 31556952) % 86400) % 3600) / 60)
, sMinutes = pluralize(minutes, 'minute')
;
if (sMinutes) {
segments.push(sMinutes);
}
var seconds = (((seconds % 31556952) % 86400) % 3600) % 60
, sSeconds = pluralize(seconds, 'second')
;
var tmp = segments.join(', ');
if (!sSeconds) {
return tmp;
}
return tmp + ' and ' + sSeconds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment