var startDateTime = '15.04.2019 00:15';
var endDateTime = '17.05.2019 18:35';
var checkDateTime = '16.04.2019 13:15';
function(checkDateTime, startDateTime, endDateTime) {
// need codes to return true or false,.
// check "checkDateTime" is between "startDateTime" to "endDateTime"
}
答案 0 :(得分:2)
尝试以下代码:
var startDateTime = getDate('15.04.2019 00:15');
var endDateTime = getDate('17.05.2019 18:35');
var checkDateTime = getDate('16.04.2019 13:15');
function isBetween(checkDateTime, startDateTime, endDateTime) {
return (checkDateTime >= startDateTime && checkDateTime <= endDateTime);
}
function toDate(str){
var [ dd, MM, yyyy, hh, mm ] = str.split(/[. :]/g);
return new Date(`${MM}/${dd}/${yyyy} ${hh}:${mm}`);
}
console.log(isBetween(checkDate,startDate,endDate));
要进行比较,请在同一天的时间间隔之间进行比较:-
var startTime = "00:35";
var endTime = "18:15";
var checkTime = "13:00";
function getMinutes(timeString){
let [hh, mm] = timeString.split(":");
return parseInt(hh)*60 + parseInt(mm);
}
function isTimeBetween(checkTime,startTime,endTime){
checkTime = getMinutes(checkTime);
return (checkTime >= getMinutes(startTime) && checkTime <= getMinutes(endTime));
}
console.log(isTimeBetween(checkTime,startTime,endTime));
答案 1 :(得分:1)
您可以使用new Date()。getTime()获取自Unix纪元以来的毫秒数。这样您就可以将日期/时间与该功能的结果进行比较。您可以这样做:
return new Date(startDateTime).getTime() <= new Date(checkDateTime).getTime() <= new Date(endDateTime).getTime();
检查一下: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
答案 2 :(得分:1)
我建议检查一下checkDateTime是否大于startDateTime小于endDateTime。
function checkDateTime(checkDateTime, startDateTime, endDateTime) {
return (new Date(startDateTime) >= new Date(checkDateTime))
&& (new Date(checkDateTime) <= new Date(endDateTime));
}
答案 3 :(得分:1)
这里是将方法直接添加到Date原型的另一个选项:
var startDateTime = new Date('04/15/2019 00:15');
var endDateTime = new Date('05/17/2019 18:35');
var checkDateTime = new Date('04/16/2019 13:15');
var outOfRangeDate_EARLY = new Date('01/16/2019 13:15');
var outOfRangeDate_LATE = new Date('06/16/2019 13:15');
Date.prototype.inRange = function(startDate, endDate){
var this_ms = this.getTime();
return ( this_ms >= startDate.getTime() && this_ms <= endDate.getTime() )
}
/* Tests */
console.log('expected: true', 'actual:', checkDateTime.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_EARLY.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_LATE.inRange(startDateTime, endDateTime))
这样,在您拥有var someDate
的任何日期中,您都可以致电someDate.inRange(startDate, endDate)
。但是,有时候,如果不小心,弄乱本地原型可能会再次困扰您。如果是这样,那么拥有其他人可以回答的独立功能非常好。
最后,在创建Date
对象之前正确格式化日期字符串非常重要,否则您会经常遇到Invalid Date
。我希望这会有所帮助。