我需要检查字符串是否在NOW和5分钟前之间
我已经设法获得了当前日期和时间以及5分钟前的信息,但是我在比较这两个日期方面很费力。
我所拥有的是一门可以打印一些日期的班级,我需要确定其中一个日期是否在过去5分钟之内
HTML:
<span class="msl_info">You have responded 3 times: on 21 Sep 2018 at 10:49, 21 Sep 2018 at 10:40, 21 Sep 2018 at 10:15.</span>
JavaScript:
var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var hour = d.getHours();
var minute = d.getMinutes();
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
//var x = document.getElementById("demo");
var hour = addZero(d.getHours());
var minute = addZero(d.getMinutes());
var minuteAgo = addZero(d.getMinutes() - 5);
//x.innerHTML = h + ":" + m;
//Today minus 5 minutes
var dateFrom = curr_date + " " + m_names[curr_month] + " " + curr_year + " at " + hour + ":" + minuteAgo;
//Now
var dateTo = curr_date + " " + m_names[curr_month] + " " + curr_year + " at " + hour + ":" + minute;
console.log(dateFrom); //21 Sep 2018 at 10:38
console.log(dateTo); // 21 Sep 2018 at 10:43
这是一个fiddle
答案 0 :(得分:0)
有关如何解决问题的快速示例:
const e = document.getElementById('msl_info');
const dates = e.innerHTML.match(/(\d{2}\s\w{3}\s\d{4}\sat\s\d{2}:\d{2})/g);
const realDates = dates.map((date) => {
const regExp = /(\d{2}\s\w{3}\s\d{4})\sat\s(\d{2}:\d{2})/;
const parsedDate = regExp.exec(date);
return Date.parse(parsedDate[1] + ' ' + parsedDate[2]);
});
function isDateInsideInterval(date) {
const now = new Date().getTime();
const past = new Date(now - (5 * 60 * 1000)).getTime();
return date >= past && date <= now ? true : false;
}
realDates.forEach((date) => {
console.log('Is in interval: ', isDateInsideInterval(date));
});
<span id="msl_info" class="msl_info">You have responded 3 times: on 21 Sep 2018 at 14:16, 21 Sep 2018 at 10:40, 21 Sep 2018 at 14:15.</span>
我阅读了您的跨度内容以查找日期。我将日期转换为日期并检查间隔。