0

The code is as follows.

let dateString1 = '2019-4';
let dateString2 = '2019-04';

(new Date(dateString1).getTime()) == (new Date(dateString2).getTime()) // false #comparison1
new Date(dateString1).getTime(); // 1554058800000 #time1
new Date(dateString2).getTime(); // 1554076800000 #time2

I know why #comparison1 is false. I just want to know the reason why #time1 and #time2 are two different values? Shouldn't these values be same?

Mukarram Ishaq
  • 748
  • 1
  • 8
  • 18
  • 1
    `2019-4` or `2019-04` is not a valid date. – random Jul 10 '19 at 11:51
  • when you pass these values to Date object, it gives me the same date – Mukarram Ishaq Jul 10 '19 at 11:52
  • @Lain why the comparison is false is because these two time values are different. I want to know why these two values are different on the basis on passed date strings? – Mukarram Ishaq Jul 10 '19 at 11:54
  • `(new Date('2019-4').getTime()) === (new Date('2019-04').getTime())` gives true for me (firefox). – Roland Starke Jul 10 '19 at 11:54
  • @RolandStarke it is giving me false on google-chrome v8 engine – Mukarram Ishaq Jul 10 '19 at 11:55
  • 5
    When you use a malformed date is will try and decode in locale time, if you on the other hand start to send a ISO date, it will use UTC. But in both cases a none valid date to the date constructor is not supported. – Keith Jul 10 '19 at 11:56
  • 4
    @MukarramIshaq "when you pass these values to Date object, it gives me the same date" ...maybe, but not the same _time_. https://jsfiddle.net/879ujzty/ . You are providing invalid strings for it to parse, so you can't expect predictable behaviour from the Date engine anyway. Keith is right about the way it attempts to interpret what you've provided, but it's only an attempt, not a guaranteed functionality. – ADyson Jul 10 '19 at 11:56
  • 1
    You can check [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters) to get documentation (there is more in-depth detail in the links which are provided there as well) about what is considered a valid date/time string which you can pass to the JS Date constructor and get predictable, documented, supported behaviour in return. – ADyson Jul 10 '19 at 11:58
  • @ADyson thanks for the documentation link. It surely helped me. – Mukarram Ishaq Jul 10 '19 at 12:08
  • @MukarramIshaq No problem. In my (humble) opinion, MDN should be the go-to place to look when you want to know something about how JavaScript, HTML, CSS etc are supposed to work. There is a lot of detail and it's usually very accurate. – ADyson Jul 10 '19 at 12:17

0 Answers0