0

I have two dates, 1 being new Date(); and another Date in the same format, I would like to check if another Date is within 1 minute.

For example if I have the Date Sun Feb 25 2018 21:57:44 GMT+0000 (GMT Standard Time), anything between Sun Feb 25 2018 21:56:44 GMT+0000 (GMT Standard Time) and Sun Feb 25 2018 21:58:44 GMT+0000 (GMT Standard Time) would count as true.

I have tried to converting it to an ISOString and then slicing it down to the 2nd integer of the minutes and comparing them like so:

parseInt(new Date().toISOString().slice(0, 16).split(':')[1]);

but I think that's inefficient, and it doesn't consider the day/date/hour.

How would I go about doing this?

newbie
  • 1,551
  • 1
  • 11
  • 21
  • Have you considered using [Moment.js](http://momentjs.com/)? – Etheryte Feb 25 '18 at 22:13
  • "*… two dates, 1 being new Date(); and another Date in the same format…*" is a non-sequteur. A Date object doesn't have a format. What you are really asking is how to parse a date string or timestamp. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) then simply subtract one date from the other to get the difference in milliseconds. – RobG Feb 25 '18 at 22:15

2 Answers2

1

Something like this:

const f = (d1, d2) => {
 if(d1.getTime() > d2.getTime())
  return d1.getTime() - d2.getTime() <= 60000; 
 return d2.getTime() - d1.getTime() <= 60000;
}

console.log(f(new Date(2018,25,2,21,57,44), new Date(2018,25,2,21,58,44)))  //true
console.log(f(new Date(2018,25,2,21,57,44), new Date(2018,25,2,21,56,44)))  //true
console.log(f(new Date(2018,25,2,21,57,44), new Date(2018,25,2,21,56,43)))  //false

60000 is one minute converted to milliseconds.

Mik378
  • 21,881
  • 15
  • 82
  • 180
0

You could do something like this:

const compareDates = (a, b) => {
    const oneMinute = 1000 * 60;
    return a >= (b - oneMinute);
}

Use it like so:

const firstDate = new Date('2017-02-25T22:05:01.0Z');

const secondDate = new Date('2017-02-25T22:05:59.0Z');

const thirdDate = new Date('2017-02-25T22:06:59.0Z');

compareDates(firstDate, secondDate);
// true

compareDates(firstDate, thirdDate);
// false
Tim Novis
  • 201
  • 2
  • 9