Js判断日期是昨天、今天或明天,以及从日期中分别取出年月日时分秒

Js判断日期是昨天、今天或明天,以及从日期中分别取出年月日时分秒

一月 11, 2022
该文章更新于 2022.01.11

直接上源码:

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
let yesterdayStr = '2022-01-10 12:20:45'
let todayStr = '2022-01-11 09:18:22'
let tomorrowStr = '2022-01-12 10:22:34'
let dayAfterTomorrow = '2022-01-13 10:23:34'

/*
* 判断昨今明
* */
function caleDate(dayStr) {
dayStr = new Date(dayStr).setHours(0, 0, 0, 0);
let today = new Date().setHours(0, 0, 0, 0);
let dateObj = {
'-86400000': '昨天',
0: '今天',
86400000: '明天'
}
return dateObj[dayStr - today] || '超出昨今明范围';
}

console.log(caleDate(yesterdayStr))
console.log(caleDate(todayStr))
console.log(caleDate(tomorrowStr))
console.log(caleDate(dayAfterTomorrow))

/*
* 获取年月日时分秒
* */
function getDate(dateStr) {
let timeArr = dateStr.replace(" ", ":").replace(/\:/g, "-").split("-");
if (timeArr.length < 6) return '格式错误'
let result = {
year: timeArr[0],
month: timeArr[1],
day: timeArr[2],
hour: timeArr[3],
minute: timeArr[4],
seconds: timeArr[5]
}
return result;
}

console.log(getDate(yesterdayStr))
console.log(getDate('传一个错误格式'))

运行结果:

image-20220111230817454