Skip to content

Instantly share code, notes, and snippets.

@Radagaisus
Created September 1, 2011 01:54
Show Gist options
  • Save Radagaisus/1185226 to your computer and use it in GitHub Desktop.
Save Radagaisus/1185226 to your computer and use it in GitHub Desktop.
Pretty Date
/*
**prettyDate** is based on [John Resig's work][1].
[1]: http://ejohn.org/blog/javascript-pretty-date/ "prettyDate"
*/
/* PrettyDate - http://ejohn.org/blog/javascript-pretty-date/
------------------------------------------------------------------/
/*
* JavaScript Pretty Date
* Copyright (c) 2008 John Resig (jquery.com)
* Licensed under the MIT license.
*
* modified version.
* added other days representation.
* removed replace(/[TZ]/g," ") was replaced me Tuesdays.
*/
// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
var date = new Date((time || "").replace(/-/g,"/")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
return date.toDateString()
.replace('Sun', 'Sunday,')
.replace('Mon', 'Monday,')
.replace('Tue', 'Tuesday,')
.replace('Wed', 'Wednesday,')
.replace('Thu', 'Thursday,')
.replace('Fri', 'Friday,')
.replace('Sat', 'Saturday,')
.replace('Jan', 'January')
.replace('Feb', 'February')
.replace('Mar', 'March')
.replace('Apr', 'April')
.replace('Jun', 'June')
.replace('Jul', 'July')
.replace('Aug', 'August')
.replace('Sep', 'September')
.replace('Oct', 'October')
.replace('Nov', 'November')
.replace('Dec', 'Deceber')
.replace(/\s(?=\d\d\B)/,", ") // add comma before the year
.replace(/\s0(?=\d\b)/,' '); // remove the zero from 01 in the day
return day_diff == 0 && (
diff < 60 && "just now" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment