Created
June 4, 2015 00:16
-
-
Save awendland/d12a8167b99099127590 to your computer and use it in GitHub Desktop.
JS function that takes an ISO time and returns a string representing how long ago the date represents.
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
/* | |
* JavaScript Pretty Date | |
* Copyright (c) 2011 John Resig (ejohn.org) | |
* Licensed under the MIT and GPL licenses. | |
*/ | |
// Takes an ISO time and returns a string representing how | |
// long ago the date represents. | |
function prettyDate (time) { | |
var date = time instanceof Date ? time : new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")), | |
diff = (((new Date()).getTime() - date.getTime()) / 1000), | |
day_diff = Math.floor(diff / 86400); | |
if (diff < 60) { | |
return "just now" | |
} | |
else if (diff < 120) { | |
return "1 minute ago"; | |
} | |
else if (diff < 3600) { | |
return Math.floor( diff / 60 ) + " minutes ago"; | |
} else if (diff < 7200) { | |
return "1 hour ago"; | |
} else if (diff < 86400) { | |
return Math.floor( diff / 3600 ) + " hours ago"; | |
} else if (day_diff == 1) { | |
return "Yesterday"; | |
} else if (day_diff < 7) { | |
return day_diff + " days ago"; | |
} else if (day_diff < 31) { | |
return Math.ceil( day_diff / 7 ) + " weeks ago"; | |
} else { | |
var months = [ "January", "February", "March", "April", "May", "June", | |
"July", "August", "September", "October", "November", "December" ]; | |
return months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment