js中Date,计算日期,当前日期前多少天的日期 两个日期相减或相加,根据传入的当前时区时间计算对应的北京时间

首先要给Date内置函数添加一个方法用于格式化时间

// 扩展date的时间格式化
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
            );
    return fmt;
};

以上Format函数是直接加在Date的原型上 可以直接用 new Date().Format("yyyy-MM-dd")调用

下面是一些常用的日期计算

根据一个日期计算出他的前30天的日期

const stratTime = '2021.7.01'
const day = 30
new Date(new Date(stratTime).getTime()-1000*60*60*24*day).Format("yyyy-MM-dd")

根据一个日期减去另一个日期 得出期间有多少天

const stratTime = '2021.7.01'

const endTime = '2021.7.11'
new Date(endTime ).getTime()-new Date(stratTime).getTime())/1000/60/60/24

计算目标月天数 起始日期以及结束日期

getMonthStratAndEnd(data){
	// 根据传入格式分割  我这里传入的是 yyyy-MM-dd格式 因此用的 -
	let newTimeList = data.split('-')
  	//本月的开始时间
   	let monthStartDate = new Date(newTimeList[0], parseInt(newTimeList[1]) - 1, 1)
   	//本月的结束时间
   	let monthEndDate = new Date(newTimeList[0], parseInt(newTimeList[1]), 0)
   	let MonthStratAndEnd = []
   	// Format为本博客最上面的函数
   	MonthStratAndEnd[0] = new Date(monthStartDate).Format('yyyy-MM-dd');//s
   	MonthStratAndEnd[1] = new Date(monthEndDate).Format('yyyy-MM-dd');//s
   	// 将数组MonthStratAndEnd返回 第一个元素为月的起始日期  第二个元素为月的结束日期
   	return MonthStratAndEnd
}	

扩展date 根据传入的当前时区时间计算对应的北京时间

// 参数一: 传入时间  参数二: 返回日期格式
Date.prototype.getBeiJingDate = function () {
    let computingTime = null
    // 通过new Date()获得当前时区并计算与北京时区差值
    let Difference = (parseInt(new Date().getTimezoneOffset() / 60) + 8) * 3600 * 1000
    // console.log('DifferenceDifference', Difference)
    // 当前日期加上时差就是北京时间
    computingTime = new Date().getTime() + Difference
    return new Date(computingTime).Format('yyyy-MM-dd hh:mm:ss')
};
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值