獲取系統當前時間與自己寫的固定時間相比較,固定時間也可以從後臺傳過來,只需用${}接收一下就行啦,提示一下,後臺傳過來的必須是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(當前日期等於固定的日期);
}
})