time.js
1.59 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
57
58
59
60
/*
yoho客服 im: 时间模块
@author acgpiano
Time.long() 返回年月日模块
Time.short() 返回小时模块
*/
class Time {
constructor(timestamp) {
this.timestamp = new Date(timestamp);
}
// 日期格式化
_format(timestamp, fmt) {
let o = {
'M+': timestamp.getMonth() + 1,
'd+': timestamp.getDate(),
'h+': timestamp.getHours(),
'm+': timestamp.getMinutes(),
's+': timestamp.getSeconds(),
'q+': Math.floor((timestamp.getMonth() + 3) / 3),
S: timestamp.getMilliseconds(),
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (timestamp.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ?
(o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return fmt;
}
// 时间对比返回
show() {
let timef = this._format(this.timestamp, 'yyyy.MM.dd'),
now = this._format(new Date(), 'yyyy.MM.dd');
if (timef === now) {
timef = this._format(this.timestamp, 'hh:mm');
} else {
timef = this._format(this.timestamp, 'yyyy.MM.dd hh:mm');
}
return this.render(timef);
}
render(timef) {
return `<div class="chat-time">
${timef}
</div>`;
}
}
export function time(timestamp) {
return new Time(timestamp);
}