直接上源码:
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('传一个错误格式'))
运行结果: