Last active
August 16, 2016 20:46
-
-
Save davelnewton/a1371867527c5f1530498e1555e2fb0a to your computer and use it in GitHub Desktop.
Date Formatting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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