获取系统当前时间与自己写的固定时间相比较,固定时间也可以从后台传过来,只需用${}接收一下就行啦,提示一下,后台传过来的必须是long类型的时间(1576032058000)
$(function(){
var t;
t = window.setInterval(function(){
var nowDate = new Date();
var year= nowDate.getFullYear();
var month = nowDate.getMonth()+1;
var today = nowDate.getDate();
var hours = nowDate.getHours();
var minutes = nowDate.getMinutes();
var seconds = nowDate.getSeconds();
if(month >= 1 && month <=9){month = "0" + month;}
if(today >= 1 && today <=9){today = "0" + today;}
var currentdate = year + "-" + month + "-" + today + " " + hours + ":" +minutes + ":" +seconds;
var currentDateLong = new Date(currentdate.replace(new RegExp("-","gm"),"/")).getTime();//当前时间
var settime=new Date("2019/12/11 10:41:30").getTime();//固定时间
if(currentDateLong>settime){//当前时间大于指定时间
stop();
}else{
console.log(currentDateLong);
}
}, 1000);
function stop(){
console.log("当前时间大于固定时间。停止计时");
window.clearInterval(t);
}
})
上一种是以时间戳的形式比较的,也就是数字。
这种是以时间格式来比较的,比较不了大小
function formatDate(date, format) {
if (!date) return;
if (!format) format = "yyyy-MM-dd HH:mm:ss";
switch(typeof date) {
case "string":
date = new Date(date.replace(/-/, "/"));
break;
case "number":
date = new Date(date);
break;
}
if (!date instanceof Date) return;
var dict = {
"yyyy": date.getFullYear(),
"M": date.getMonth() + 1,
"d": date.getDate(),
"H": date.getHours(),
"m": date.getMinutes(),
"s": date.getSeconds(),
"MM": ("" + (date.getMonth() + 101)).substr(1),
"dd": ("" + (date.getDate() + 100)).substr(1),
"HH": ("" + (date.getHours() + 100)).substr(1),
"mm": ("" + (date.getMinutes() + 100)).substr(1),
"ss": ("" + (date.getSeconds() + 100)).substr(1)
};
return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function() {
return dict[arguments[0]];
});
}
$(function(){
if(formatDate(new Date(),"yyyy-MM-dd") == "2019-12-15" ){
alert(当前日期等于固定的日期);
}
})