day.js
1.69 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import {isNull, isUndefined} from 'lodash';
class Day {
constructor(date) {
if (isNull(date) || isUndefined(date)) {
this._date = new Date();
} else {
this._date = new Date(date);
}
this._init();
}
_init() {
const { _date } = this;
this._date_y = _date.getFullYear();
this._date_M = _date.getMonth() + 1;
this._date_D = _date.getDate();
this._date_W = _date.getDay();
this._date_H = _date.getHours();
this._date_m = _date.getMinutes();
this._date_s = _date.getSeconds();
this._date_ms = _date.getMilliseconds();
}
_get(type) {
return this[`_date_${type}`];
}
_fix(num, length) {
num = num + '';
return num.length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : num;
}
year() {
return this._get('y');
}
month() {
return this._get('M');
}
day() {
return this._get('W');
}
date() {
return this._get('D');
}
hour() {
return this._get('H');
}
minute() {
return this._get('m');
}
second() {
return this._get('s');
}
millisecond() {
return this._get('ms');
}
fromNow() {
const date = this._date.getTime();
const today = new Date(new Date().toLocaleDateString()).getTime();
const days = Math.floor((today - date) / (24 * 60 * 60 * 1000)) + 1;
if (days > 5) {
return `${this.year()}-${this._fix(this.month(), 2)}-${this._fix(this.day(), 2)}`;
} else if (days > 2) {
return '2天前';
} else if (days > 1) {
return '前天';
} else if (days > 0) {
return '昨天';
} else {
return `${this.hour()}:${this.minute()}`;
}
}
}
function day(date) {
return new Day(date);
}
export default day;