1

This is driving me crazy for an hour.

Here is a snap shot of my Chrome console.

You can see how the default js Date() function is behaving so inconsistently with different dateTime string provided to it.

enter image description here

Anyone knows anything? How should I deal with it?

Thanks

TypingPanda
  • 1,607
  • 3
  • 19
  • 32
  • 4
    It looks like it's parsing the string as `mm/dd/yyyy`, whereas your format is `dd/mm/yyyy` – Casey Chu Sep 23 '15 at 06:37
  • 1
    For the ten zillionth time, **do not parse date strings with the Date constructor**, it **will** fail. Manually parse the string. I can't see the image, you should post actual, runnable code and the results. A function to parse a date string should be no more than 2 or 3 lines of code. – RobG Sep 23 '15 at 06:40
  • chrome takes date format as `mm/dd/yyyy` – J Santosh Sep 23 '15 at 06:44
  • @RobG, If it only takes a couple lines of code, are you still using the Date class, just not the Date constructor? – Alex Sep 23 '15 at 06:51
  • @Alex—the only way to create a Date object is to use the Date constructor. JavaScript doesn't have classes. – RobG Sep 23 '15 at 07:19

2 Answers2

0

Your format is wrong. There is no 30th month. Try this,

new Date("09/30/2015 11:59:59 PM")

khadi
  • 1
0

Some browser use the "dd/mm/yyyy" format, other "mm/dd/yyyy" and so on, either way, for you to not get invalid date you need to know which format the date class/function/method will use so you can pass the date string in that order.

Obviously the browser you tested on use "mm/dd/yyyy" and therefore your first date is invalid as there exist no a month with number "30" as in "30/09/2015".

Of course it would be clever if browser could guess and in this case it would be easy but this, "10/12/2015", it wouldn't, as both the "mm/dd/yyyy" and "dd/mm/yyyy" will have a corresponding real date, "10 of Dec" and "12 of Oct", and we can't let the browser decide which one is the one we mean, as both will pass as valid.

Check this question for a deep dive into the issue and as well a couple of ways how to solve it - Why does Date.parse give incorrect results?

Community
  • 1
  • 1
Asons
  • 84,923
  • 12
  • 110
  • 165