· 9 years ago · Nov 29, 2016, 06:14 PM
1/*
2 * Javascript Humane Dates
3 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
4 * Re-write by Zach Leatherman (zachleat.com)
5 *
6 * Adopted from the John Resig's pretty.js
7 * at http://ejohn.org/blog/javascript-pretty-date
8 * and henrah's proposed modification
9 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
10 *
11 * Licensed under the MIT license.
12 */
13
14function humaneDate(date, compareTo){
15
16 if(!date) {
17 return;
18 }
19
20 var lang = {
21 ago: 'Ago',
22 from: '',
23 now: 'Just Now',
24 minute: 'Minute',
25 minutes: 'Minutes',
26 hour: 'Hour',
27 hours: 'Hours',
28 day: 'Day',
29 days: 'Days',
30 week: 'Week',
31 weeks: 'Weeks',
32 month: 'Month',
33 months: 'Months',
34 year: 'Year',
35 years: 'Years'
36 },
37 formats = [
38 [60, lang.now],
39 [3600, lang.minute, lang.minutes, 60], // 60 minutes, 1 minute
40 [86400, lang.hour, lang.hours, 3600], // 24 hours, 1 hour
41 [604800, lang.day, lang.days, 86400], // 7 days, 1 day
42 [2628000, lang.week, lang.weeks, 604800], // ~1 month, 1 week
43 [31536000, lang.month, lang.months, 2628000], // 1 year, ~1 month
44 [Infinity, lang.year, lang.years, 31536000] // Infinity, 1 year
45 ],
46 isString = typeof date == 'string',
47 date = isString ?
48 new Date(('' + date).replace(/-/g,"/").replace(/[TZ]/g," ")) :
49 date,
50 compareTo = compareTo || new Date,
51 seconds = (compareTo - date +
52 (compareTo.getTimezoneOffset() -
53 // if we received a GMT time from a string, doesn't include time zone bias
54 // if we got a date object, the time zone is built in, we need to remove it.
55 (isString ? 0 : date.getTimezoneOffset())
56 ) * 60000
57 ) / 1000,
58 token;
59
60 if(seconds < 0) {
61 seconds = Math.abs(seconds);
62 token = lang.from ? ' ' + lang.from : '';
63 } else {
64 token = lang.ago ? ' ' + lang.ago : '';
65 }
66
67 /*
68 * 0 seconds && < 60 seconds Now
69 * 60 seconds 1 Minute
70 * > 60 seconds && < 60 minutes X Minutes
71 * 60 minutes 1 Hour
72 * > 60 minutes && < 24 hours X Hours
73 * 24 hours 1 Day
74 * > 24 hours && < 7 days X Days
75 * 7 days 1 Week
76 * > 7 days && < ~ 1 Month X Weeks
77 * ~ 1 Month 1 Month
78 * > ~ 1 Month && < 1 Year X Months
79 * 1 Year 1 Year
80 * > 1 Year X Years
81 *
82 * Single units are +10%. 1 Year shows first at 1 Year + 10%
83 */
84
85 function normalize(val, single)
86 {
87 var margin = 0.1;
88 if(val >= single && val <= single * (1+margin)) {
89 return single;
90 }
91 return val;
92 }
93
94 for(var i = 0, format = formats[0]; formats[i]; format = formats[++i]) {
95 if(seconds < format[0]) {
96 if(i === 0) {
97 // Now
98 return format[1];
99 }
100
101 var val = Math.ceil(normalize(seconds, format[3]) / (format[3]));
102 return val +
103 ' ' +
104 (val != 1 ? format[2] : format[1]) +
105 (i > 0 ? token : '');
106 }
107 }
108};