· 9 years ago · Aug 30, 2016, 09:50 PM
1/*
2 * JavaScript Pretty Date
3 * Copyright (c) 2011 John Resig (ejohn.org)
4 * Licensed under the MIT and GPL licenses.
5
6 * prettyDate("2008-01-28T20:24:17Z") // => "2 hours ago"
7 * prettyDate("2008-01-27T22:24:17Z") // => "Yesterday"
8 * prettyDate("2008-01-26T22:24:17Z") // => "2 days ago"
9 * prettyDate("2008-01-14T22:24:17Z") // => "2 weeks ago"
10 * prettyDate("2007-12-15T22:24:17Z") // => undefined
11 * Takes an ISO time and returns a string representing how
12 * long ago the date represents.
13 */
14function prettyDate(time) {
15 var date = new Date((time || "").replace(/-/g, "/").replace(/[TZ]/g, " ")),
16 diff = (((new Date()).getTime() - date.getTime()) / 1000),
17 day_diff = Math.floor(diff / 86400);
18
19 if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) return;
20
21 return day_diff == 0 && (
22 diff < 60 && "just now" ||
23 diff < 120 && "1 minute ago" ||
24 diff < 3600 && Math.floor(diff / 60) + " minutes ago" ||
25 diff < 7200 && "1 hour ago" ||
26 diff < 86400 && Math.floor(diff / 3600) + " hours ago") ||
27 day_diff == 1 && "Yesterday" ||
28 day_diff < 7 && day_diff + " days ago" ||
29 day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago";
30}
31
32// If jQuery is included in the page, adds a jQuery plugin to handle it as well
33if (typeof jQuery != "undefined") jQuery.fn.prettyDate = function() {
34 return this.each(function() {
35 var date = prettyDate(this.title);
36 if (date) jQuery(this).text(date);
37 });
38};