-
Notifications
You must be signed in to change notification settings - Fork 3
/
jquery.timediff.js
89 lines (88 loc) · 3.71 KB
/
jquery.timediff.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* This script is freely available without charge and without warranty.
*
* Author: T. Jaskowski
* Site: https://github.com/tadeck
* Version: 0.1.1
*/
(function ($, window) {
'use strict';
/**
* Apply timediff plugin on specific elements (passing some options, if
* necessary), or disable it on specific elements (passing "off" string).
* @param {object|String} options object containing options, or string action
* @returns {jQuery}
*/
$.fn.timediff = function (options) {
var data_interval_key = 'jquery-timediff-interval',
clearInt = window.clearInterval,
setInt = window.setInterval,
abs = window.Math.abs,
floor = window.Math.floor,
opts;
if (options === 'off') {
// this call is meant to disable all the currently playing timediffs
return this.each(function () {
var interval = $(this).data(data_interval_key);
if (interval) {
clearInt(interval);
}
});
} else {
// calculate options with defaults
opts = $.extend({
'attr': 'datetime',
'description_calc': function (diff, timestamp_calc) {
var in_past = (diff >= 0);
return (in_past ? '' : 'in ') + timestamp_calc(diff) + (in_past ? ' ago' : '');
},
'interval': 1000,
'timestamp_calc': function (diff) {
diff = abs(diff); // we do not care, if it is in the past
var result = [],
tmp_diff = floor(diff / 31536000); // 365 days
if (tmp_diff) {
result.push(tmp_diff + ' year' + (tmp_diff !== 1 ? 's' : ''));
diff -= tmp_diff * 31536000;
}
tmp_diff = floor(diff / 2592000); // 30 days
if (tmp_diff) {
result.push(tmp_diff + ' month' + (tmp_diff !== 1 ? 's' : ''));
diff -= tmp_diff * 2592000;
}
tmp_diff = floor(diff / 86400);
if (tmp_diff) {
result.push(tmp_diff + ' day' + (tmp_diff !== 1 ? 's' : ''));
diff -= tmp_diff * 86400;
}
tmp_diff = floor(diff / 3600);
if (tmp_diff) {
result.push(tmp_diff + ' hour' + (tmp_diff !== 1 ? 's' : ''));
diff -= tmp_diff * 3600;
}
tmp_diff = floor(diff / 60);
if (tmp_diff) {
result.push(tmp_diff + ' minute' + (tmp_diff !== 1 ? 's' : ''));
diff -= tmp_diff * 60;
}
if (diff) {
// seconds left
result.push(diff + ' second' + (diff !== 1 ? 's' : ''));
}
return result.join(' ');
}
}, options);
return this.each(function () {
var el = $(this),
time_base = new Date(el.attr(opts.attr)),
update_time = function () {
el.text(opts.description_calc(floor(((new Date()) - time_base) / 1000), opts.timestamp_calc));
},
interval;
update_time(); // first call - do not wait for interval
interval = setInt(update_time, opts.interval);
el.data(data_interval_key, interval); // save interval ID
});
}
};
}(jQuery, window));