0

I have a date like this in DB:

  1. 2020-10-21T00:06:06.000Z which I want to compare with current date and time

If current date and time has past the date from DB then trigger some action.

let oldDate = `2020-10-21T00:06:06.000Z`;
let dateNow = new Date();
console.log('oldDate ', new Date(oldDate));
console.log('date now', dateNow);
console.log('oldDate time', new Date(oldDate).getTime());
console.log('newDate time', dateNow.getTime());

const schedule = dateNow.getTime() > new Date(oldDate).getTime() ? "trigger now" : "trigger later";
console.log('scheduled for:  ', schedule);

I am trying to check if dateTime is past old dateTime but is this is right approach or any other better solutions?

kittu
  • 6,662
  • 21
  • 91
  • 185
  • ISO 8601 timestamps will naturally sort themseves into "newer" and "older" if you check for "less than" and "greater than": `"2020-01-20" > "2020-02-20" //false` while `"2020-01-20" < "2020-02-20" //true` – VLAZ Oct 21 '20 at 09:56
  • @VLAZ If I don't use `getTime()` result is invalid – kittu Oct 21 '20 at 10:00
  • Then you don't have ISO 8601 formatted dates. – VLAZ Oct 21 '20 at 10:00
  • @VLAZ `2020-10-21T00:06:06.000Z` ?? – kittu Oct 21 '20 at 10:03
  • 1
    If you're getting an invalid result, then your formats are wrong somewhere. That's all I can say - lexicographic sorting also acts as chronological for ISO 8601 strings. That's part of the design behind the standard. You receiving wrong results means that there is something non-standard happening. [JSBin](https://jsbin.com/penekamezu/1/edit) – VLAZ Oct 21 '20 at 10:07

1 Answers1

1

Sorry, not enough reputation to make a comment. Did you try this?

let oldDate = '2020-10-21T00:06:06.000Z';
const schedule = Date.now() - Date.parse(oldDate) > 0 ? "trigger now" : "trigger later";
B_Joker
  • 99
  • 5
  • Yes I just did and now trying to understand difference between `Date.parse(oldDate)` and `new Date(oldDate).getTime()` – kittu Oct 21 '20 at 10:05
  • Well the first idea and the most obvious point is the Date.parse is a static method whilst with new Date() approach you construct a new instance. Subtle difference though. – B_Joker Oct 21 '20 at 10:08
  • 1
    Date.parse() also creates a new instance - it's just a static factory method: https://stackoverflow.com/a/929273/9150652 – MauriceNino Oct 21 '20 at 10:57
  • @MauriceNino Date.parse() returns a primitive type number. Not an instance. So IMHO static factory pattern does not relate that case. – B_Joker Oct 21 '20 at 12:20
  • Ahhh should have looked into what Date.parse() does lol, my mistake. Caught offguard by that "subtle difference", so I thought both return a date object. Youre right - but the difference is not so subtle :P – MauriceNino Oct 21 '20 at 13:17