-
Notifications
You must be signed in to change notification settings - Fork 3
/
date-format.js
67 lines (58 loc) · 1.7 KB
/
date-format.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
"use strict"
export {
timestampToString,
now,
toRfc3339,
fromRfc3339
};
// 自行实现了Date的format()函数
// https://blog.scottchayaa.com/post/2019/05/27/javascript_date_memo
Date.prototype.format = function (fmt, utc = false) {
let weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
let o = utc?{
"M+": this.getUTCMonth() + 1, //月份
"d+": this.getUTCDate(), //日
"h+": this.getUTCHours(), //小時
"m+": this.getUTCMinutes(), //分
"s+": this.getUTCSeconds(), //秒
"q+": Math.floor((this.getUTCMonth() + 3) / 3), //季度
'w+': weekdays[this.getUTCDay()],
"S": this.getUTCMilliseconds() //毫秒
} : {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小時
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
'w+': weekdays[this.getDay()],
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, ((utc ? this.getUTCFullYear():this.getFullYear()) + "").substr(4 - RegExp.$1.length));
for (let k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
if (k !== 'w+')
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
else
fmt = fmt.replace(RegExp.$1, o[k]);
}
}
return fmt;
}
const g_dateObj = new Date();
function timestampToString(ts, fmt, utc) {
g_dateObj.setTime(ts * 1000);
return g_dateObj.format(fmt, utc);
}
function now() {
return Date.now();
}
function toRfc3339(ts)
{
return timestampToString(ts, 'yyyy-MM-ddThh:mm:ssZ', true);
}
function fromRfc3339(str)
{
return parseInt(Date.parse(str) / 1000);
}