//第一位表示距离今天还有几天,如0表示今天,1表示明天,-1表示昨天
//第二位表示指定日期,默认不传为今天,支持格式'2020-10-10', '2020/01/01'
function getTargetDate(num = 0, baseDate = null) {
let tarDate = ''//目标日期
if (baseDate) {
tarDate = new Date(baseDate);
} else {
tarDate = new Date();
}
//如果num不为0 说明要推移时间,需要把基础时间转换成时间戳的形式进行计算
if (num !== 0) {
tarDate = tarDate.getFullYear() + '-' + (tarDate.getMonth() + 1) + '-' + tarDate.getDate() + ' 00:00:00';// Year-Month-Date 00:00:00
tarDate = Date.parse(tarDate.replace(/-/g, '/'));//把指定时间转换为时间戳,ie不支持‘/’,Date.parse(Year-Month-Date)
tarDate += (86400000) * num;//修改后的时间戳,24*60*60 = 86400000 一天的毫秒数
tarDate = new Date(tarDate);//时间戳转换为时间
// tarDate = new Date(tarDate.setDate(tarDate.getDate() + num))//todo 这一行代替上边四行
}
//把new Date()的形式 格式化
const weekday = [
"周日",
"周一",
"周二",
"周三",
"周四",
"周五",
"周六",
];
const y = tarDate.getFullYear();
let month = (tarDate.getMonth() + 1);
month = month < 10 ? "0" + month : month
let date = tarDate.getDate(); //直接date上加减遇见跨月的会有问题,getDate后得到一个数字,01-2 = -1
date = date < 10 ? "0" + date : date
const d = weekday[tarDate.getDay()];
let h;
h = tarDate.getHours() < 10 ? "0" + tarDate.getHours() : tarDate.getHours()
let m;
m = tarDate.getMinutes() < 10 ? "0" + tarDate.getMinutes() : tarDate.getMinutes()
let s;
s = tarDate.getSeconds() < 10 ? "0" + tarDate.getSeconds() : tarDate.getSeconds()
let resDate = `${y}-${month}-${date}`
let resNumDate = '' + y + month + date
let currentTime = `${h}:${m}:${s}`
return {
year: y,
month: month,
date: date,
weekday: d,
hour: h,
minute: m,
second: s,
resDate: resDate,//Year-Month-Date
resNumDate: resNumDate,//YearMonthDte
currentTime: currentTime,//xx:xx:xx
}
}
//支持的入参
getTargetDate().currentTime // 16:05:05
getTargetDate().resNumDate //20201212 当天
getTargetDate().resDate//2020-12-12 当天
getTargetDate(-1).resDate//2020-12-11 一天前
getTargetDate().weekday //周六
getTargetDate(2,'2022-01-18').resDate //2022-01-20,指定2022-01-18的两天后
js 格式化当前时间 日期推算
于 2022-01-25 13:32:57 首次发布