Created
September 18, 2013 00:41
-
-
Save sgreenfield/6602864 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
Date.prototype.toRelativeTime = function(date) { | |
var delta = date - this, units, conversions; | |
conversions = { | |
millisecond: 1, // ms -> ms | |
second: 1000, // ms -> sec | |
minute: 60, // sec -> min | |
hour: 60, // min -> hour | |
day: 24, // hour -> day | |
month: 30, // day -> month (roughly) | |
year: 12 // month -> year | |
}; | |
for (var key in conversions) { | |
if (delta < conversions[key]) { | |
break; | |
} else { | |
units = key; | |
delta = delta / conversions[key]; | |
} | |
} | |
if (units === 'second') return 'less than a minute'; | |
delta = Math.floor(delta); | |
if (delta !== 1) { units += "s"; } | |
return [delta, units].join(" "); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment