Object.assign(Date.prototype, {
switch(time) {
let date = {
"yy": this.getFullYear(),
// 这里月份的key采用大写,为了区别分钟的key
"MM": this.getMonth() + 1,
"dd": this.getDate(),
"hh": this.getHours(),
"mm": this.getMinutes(),
"ss": this.getSeconds()
};
//输出年 y+:匹配1个到多个y,i:忽略大小写
if (/(y+)/i.test(time)) {
time = time.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
//输出月、日、时、分、秒
Object.keys(date).forEach(function (i) {
// "(" + i + ")"的结果是字符串"(i+)",
// 只有写成"(" + i + ")"形式,才能在正则表达式中捕获子匹配,进而才能用到RegExp.$1的值
if (new RegExp("(" + i + ")").test(time)) {
// 判断,如果时间为一位数,则在前面加'0'
// ps:这里有一个小知识点:number类型+string类型 = string类型
if (RegExp.$1.length == 2) {
date[i] < 10 ? date[i] = '0' + date[i] : date[i];
}
//替换初始化函数时候传入yyyy-mm-dd hh:mm:ss(这里可以打印出time、RegExp.$1、date[k])
time = time.replace(RegExp.$1, date[i]);
}
})
return time;
}
})
function isDateExpired() { //后端返回时间 var date = JSON.parse(localStorage.getItem("photoPicker")) var beginTime = date.dateExpired //当前 let now = new Date(); // now.switch()传参的大小写要和方法内定义的key匹配 nowTime = now.switch('yyyy-MM-dd hh:mm:ss') var beginTimes = beginTime.substring(0, 10).split('-'); var endTimes = nowTime.substring(0, 10).split('-'); beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' + beginTime.substring(10, 19); nowTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + nowTime.substring(10, 19); var a = (Date.parse(beginTime) - Date.parse(nowTime)) / 3600 / 1000; console.log(Date.parse(nowTime), Date.parse(beginTime)); console.log("剩余时间为" + a); var flag = a<=0; if(flag){ SinglebtnPopup("链接已失效请重新打开页面", "确定", function (result) { CloseBrowser() }) } return flag; }