Date constructor: numeric arguments vs. string argument giving different dates in some cases

后端 未结 5 1986
孤街浪徒
孤街浪徒 2021-01-01 16:18

First of all, I think timezone probably has something to do with this. I\'m in EST/EDT. Also, I\'m testing this on chromium 17 / linux.

Now, let\'s say I create two

5条回答
  •  自闭症患者
    2021-01-01 16:40

    It looks like the date constructor requires spaces rather than '-'. Its the recommended way. Check out this link:
    3.3. Date and Time Specification

    Though foldingwhite space is permitted throughout the date-time specification, it is RECOMMENDED that a single space be used in each place that FWS appears (whether it is required or optional)

    Also check out this link:
    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

    dateString: String value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 2822 timestamps).

    I tried following code and it returns true

    dateFromNumbers = new Date(2020, 11, 15);
    dateFromString = new Date("2020 12 15");
    alert(+dateFromNumbers == +dateFromString);​
    

    Also its not a problem start with the month of October, it has do with the double digit months. If I try the same method with September then:

    dateFromNumbers = new Date(2020, 8, 15);
    dateFromString = new Date("2020-09-15");
    alert(+dateFromNumbers == +dateFromString);​ // This returns false
    

    But if I use single digit for September then it returns true

    dateFromNumbers = new Date(2020, 8, 15);
    dateFromString = new Date("2020-9-15");
    alert(+dateFromNumbers == +dateFromString);​ // This returns true
    

    And if use space with double digit September, then it returns true

    dateFromNumbers = new Date(2020, 8, 15);
    dateFromString = new Date("2020 09 15");
    alert(+dateFromNumbers == +dateFromString);​//This returns true
    

提交回复
热议问题