0

I need to check whether a string is between NOW and 5 minutes ago

I've managed to get the current date + time and the 5 minutes ago, but I'm struggling on comparing this two dates.

What I have, is a class that prints a few dates and I'd need to find if one of those dates is within the past 5 minutes

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

This is a fiddle

fabrik
  • 14,094
  • 8
  • 55
  • 71
john285
  • 53
  • 1
  • 6

1 Answers1

0

Quick example about how to solve your problem:

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>

I read your span content looking for dates. I transforn the dates into Date and check the interval.

F.bernal
  • 2,594
  • 2
  • 22
  • 27