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

const currentStartEnd = {
'day': function getCurrentDayStartEnd() {
const d = new Date()
return {
s: new Date(d.setHours(0, 0, 0, 0)),
e: new Date(d.setHours(23, 59, 59, 999))
}
},

'week': function getCurrentWeekStartEnd() {
const d = new Date()
let n = d.getDay()
if (n === 0) n = 7
const num = 24 * 60 * 60 * 1000
const s = startTime(d.valueOf() - (n - 1) * num)
return {
s: new Date(s),
e: new Date(endTime(s + 6 * num))
}
},

'month': function getCurrentMonthStartEnd() {
const d = new Date()
d.setDate(1)
const s = new Date(startTime(d))
const nm = d.getMonth() + 1
const nf = new Date(d.getFullYear(), nm, 1)
const num = 1 * 24 * 60 * 60 * 1000
const e = new Date(endTime(nf - num))

return {
s,
e
}
},
'year': function getCurrentYearStartEnd() {
const num = 1 * 24 * 60 * 60 * 1000
const s = new Date()
const e = new Date()
s.setDate(1)
s.setMonth(0)
e.setFullYear(e.getFullYear() + 1)
e.setDate(1)
e.setMonth(0)

return {s: new Date(startTime(s)), e: new Date(endTime(e - num))}
},
}

function startTime(time) {
return new Date(time).setHours(0, 0, 0, 0)
}

function endTime(time) {
return new Date(time).setHours(23, 59, 59, 999)
}

function getStartEnd(unit) {
return currentStartEnd[unit]()
}

结果

1
2
3
4
console.log(getStartEnd('day'))
console.log(getStartEnd('week'))
console.log(getStartEnd('month'))
console.log(getStartEnd('year'))