活動檔期、優惠期限、可預約的日期範圍——這些功能都需要「把現在時間跟一段區間比大小」。做法是把字串日期都轉成毫秒數(getTime)再比較。
function checkTime(stime, etime) {
// 起訖日期都是 yyyy-MM-dd 或 yyyy-M-d
var s = stime.split('-');
var e = etime.split('-');
var startTimes = new Date(s[0], s[1] - 1, s[2]).getTime();
var endTimes = new Date(e[0], e[1] - 1, e[2]).getTime();
// 現在時間只取到「日」,避免當天 00:00 之後被判定超出
var now = new Date();
var nowTimes = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
return nowTimes >= startTimes && nowTimes <= endTimes;
}
// 用法
if (checkTime('2016-8-1', '2016-8-10')) {
document.write('今天落在指定區間內');
} else {
document.write('今天不在指定區間內');
}
第一,月份少減 1。JavaScript 的 Date 建構子月份是 0 起算(0 = 一月),直接塞 8 會變成九月。上面的版本已改成 s[1] - 1。
第二,用字串拼日期補零。原本寫成 thisDate.getFullYear() + '-0' + (getMonth() + 1),遇到十月以後就會拼出「2016-010-05」這種怪字串。與其拼字串再 split 回來,不如直接把數字傳進 Date 建構子,乾淨又不容易出錯。
如果區間需要含時辰,建議統一使用可排序的字串格式(yyyy-MM-dd HH:mm:ss),並交給 Date.parse 處理。注意 Safari 對「用減號分隔」的日期時間字串支援較差,保險做法是換成斜線:
function isBetween(start, end, target) {
// 輸入格式:2016-08-01 09:00:00
var toTime = function (str) {
return new Date(str.replace(/-/g, '/')).getTime();
};
var t = toTime(target || now2str());
return t >= toTime(start) && t <= toTime(end);
}
function now2str() {
var d = new Date();
var p = function (n) { return n < 10 ? '0' + n : '' + n; };
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate())
+ ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds());
}
最後提醒一個常被忽略的細節:結束日期若只寫到「日」,new Date(2016, 7, 10) 代表的是 8 月 10 日 00:00:00,因此「8 月 10 日一整天都算檔期內」這種需求,要把結束日加一天再改成「小於」判斷,否則當天 00:00 之後一律被判為已結束。