js 格式化当前时间 日期推算

//第一位表示距离今天还有几天,如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的两天后
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值