在 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() + ""));
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;
}
// 应用:new Date(1542274800000).Format('yy-MM-dd hh:mm:ss');
Vue filter
Vue.filter('dateFilter', function (value) {if (/^[0-9]*$/.test(value)) {return new Date(value).Format('yyyy-MM-dd')
} else {return value}
})
获取指定日期的年月日
function addZero(item) {return item < 10 ? "0" + item : item;}
// 获取指定日期的前 N 天日期,startDay 默认当天
function getDate(start, end, startDay) {let day = !!startDay ? new Date(startDay) : new Date();
day.setTime(day.getTime() + start * 24 * 60 * 60 * 1000);
let s1 =
day.getFullYear() +
"-" +
addZero(day.getMonth() + 1) +
"-" +
addZero(day.getDate());
let day1 = !!startDay ? new Date(startDay) : new Date();
day1.setTime(day1.getTime() + end * 24 * 60 * 60 * 1000);
let s2 =
day1.getFullYear() +
"-" +
addZero(day1.getMonth() + 1) +
"-" +
addZero(day1.getDate());
return {
startDate: s1,
endDate: s2,
};
}
将工夫转换为 13 位工夫戳
function swtichToTimestamp(time) {if (/^[0-9]*$/.test(time)) { // 工夫戳
if (time.length > 13) {time = time.slice(0, 13)
} else {time = time + Array(14 - time.length).join("0")
}
} else { // 工夫
time = new Date(time).getTime()}
return +time
}
比拟两个工夫的差时
function getTimeDiffByType(time1, time2, type) {
let diff = time1 - time2
let base = 1000
switch (type) {
case 'day':
base = base * 60 * 60 * 24
break
case 'hour':
base = base * 60 * 60
break
case 'minute':
base = base * 60
break
}
return diff/base | 0
}