首先要给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')
};