0

I have a timestamp like new Date('2017-07-03T16:00:00.000')

I need to compare this date to the current date (new Date() without arguments) and be able to tell whether at least one day has passed by date. The time of the day does not play a role.

Here are a few examples:

Example 1
Old datetime: 2017-07-02T20:00:00.000
Current datetime: 2017-07-03T16:00:00.000
Returns true because the old date was 2nd of July 2017, the current one is 3rd of July 2017.

Example 2
Old datetime: 2017-07-02T20:00:00.000
Current datetime: 2017-07-02T22:00:00.000
Returns false because the old date was 2nd of July 2017 and the current one is 2nd of July 2017.

Example 3
Old datetime: 2017-07-02T20:00:00.000
Current datetime: 2017-07-04T22:00:00.000
Returns true because multiple days have passed since the 2nd of July 2017.

I can't come up with a simple way to do this without messing with the calendar (month-& year transitions, leapyear etc.) itself. Can you enlighten me?

Hedge
  • 16,142
  • 42
  • 141
  • 246
  • 1
    Possible duplicate of [How do I get the number of days between two dates in JavaScript?](https://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript) – Matt Jul 03 '17 at 16:50

2 Answers2

2
compare=date=>(new Date()-(1000*60*60*24))>+new Date(date));

Simply check if current - 1day > old...

If you dont want 24 hours but rather last day, you can use modulo:

compare=date=>new Date()-(new Date()%(1000*60*60*24))>+new Date(date);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Ok but with this at least 24 hours need to be passed between both datetimes. I also want to return true when its a new day (e.g. compare time was at 6 PM yesterday, you check at 2 AM today --> returns true) – Hedge Jul 03 '17 at 16:51
  • Thanks, I didn't know you can use module with Dates likes this – Hedge Jul 03 '17 at 16:58
1

function oneDayHasPassed(date1, date2) {
  const year1 = date1.getFullYear();
  const year2 = date2.getFullYear();
  const month1 = date1.getMonth();
  const month2 = date2.getMonth();
  const day1 = date1.getDate();
  const day2 = date2.getDate();

  return year2 > year1 || (year1 === year2 && (month2 > month1 || month1 === month2 && day2 > day1));
}

const tests = [
  ['2017-07-02T20:00:00.000', '2017-07-03T16:00:00.000'],
  ['2017-07-02T20:00:00.000', '2017-07-02T22:00:00.000'],
  ['2017-07-02T20:00:00.000', '2017-07-04T22:00:00.000'],
];

tests.forEach(([d1, d2]) => console.log(oneDayHasPassed(new Date(d1), new Date(d2))));