index.js
1.98 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
export function debounce(fn, delay, triggerNow) {
var t = null
var debounced = function() {
var _self = this,
args = arguments
if (t) {
clearTimeout(t)
}
if (triggerNow) {
var exec = !t
t = setTimeout(function() {
t = null
}, delay)
if (exec) {
// 初次进来
fn.apply(_self, args)
}
} else {
t = setTimeout(function() {
fn.apply(_self, args)
}, delay)
}
}
debounced.remove = function() {
clearTimeout(t)
t = null
}
return debounced
}
//格式化日期
export const formatDate = (date, fmt = '-') => {
//shijianchuo是整数,否则要parseInt转换
var time = new Date(date)
var y = time.getFullYear()
var m = time.getMonth() + 1
var d = time.getDate()
var h = time.getHours()
var mm = time.getMinutes()
var s = time.getSeconds()
return y + fmt + add0(m) + fmt + add0(d) + ' ' + add0(h) + ':' + add0(mm)
}
function add0(m) {
return m < 10 ? '0' + m : m
}
//正则表示式是干什么的? 字符串匹配利器(难,规则多)
export function formatDate2(date, fmt) {
//1.获取年份
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
//2.获取
//M+ ->正则表达式一个规则
//
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
}
}
return fmt
}
//填补左边的零(一般返回字符串最后两位)
function padLeftZero(str) {
return ('00' + str).substr(str.length)
}