-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrelative-time.js
More file actions
56 lines (49 loc) · 1.55 KB
/
Copy pathrelative-time.js
File metadata and controls
56 lines (49 loc) · 1.55 KB
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
;(function(root, factory){
var define = define || {};
if( typeof define === 'function' && define.amd )
define([], factory);
else if( typeof exports === 'object' && typeof module === 'object' )
module.exports = factory();
else if(typeof exports === 'object')
exports["RelativeTime"] = factory()
else
root.RelativeTime = factory()
}(this, function(){
// in miliseconds
const UNITS = {
year : 24 * 60 * 60 * 1000 * 365,
month : 24 * 60 * 60 * 1000 * 365/12,
day : 24 * 60 * 60 * 1000,
hour : 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000
}
const DEFAULTS = {
locale: 'en',
options: { numeric: 'auto' }
}
function RelativeTime( settings ){
settings = settings || {}
settings = {
locale: settings.locale || DEFAULTS.locale,
options: {...DEFAULTS.options, ...settings.options}
}
this.rtf = new Intl.RelativeTimeFormat(settings.locale, settings.options)
}
RelativeTime.prototype = {
// returns d1 relative to d2 time string in locale format
from(d1, d2){
const elapsed = d1 - (d2 || new Date())
// "Math.abs" accounts for both "past" & "future" scenarios
for (let u in UNITS)
if (Math.abs(elapsed) > UNITS[u] || u == 'second')
return this.rtf.format(Math.round(elapsed/UNITS[u]), u)
}
}
// Static method for convenience - creates instance per call
RelativeTime.from = function(d1, d2, locale) {
const instance = new RelativeTime(locale ? { locale } : {})
return instance.from(d1, d2)
}
return RelativeTime
}));