new Date() shows differents results in Chrome or Firefox

后端 未结 2 629
臣服心动
臣服心动 2021-01-18 11:29

Strange thing, different results in differente browser for a new Date().

In Chrome 45.0.2454.101 m:

new Date(2015,9,1)
Thu Oct 01          


        
2条回答
  •  梦谈多话
    2021-01-18 12:31

    IF you don't want the timezone offset to be included you can use Date.UTC

    Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.

    ~MDN

    Output from Firefox dev console:

    > new Date(2015,9,1)
      Date 2015-09-30T22:00:00.000Z  // reproduces your problem, my local time is GMT+0200
    > new Date(Date.UTC(2015,9,1))
      Date 2015-10-01T00:00:00.000Z // UTC time
    

    However 00:00:00 GMT+0200 and 22:00:00.000Z are just different ways to represent the timezone offset in Date's string representation. The difference is the method used when printing to console: most browsers use .toString() while Firefox uses .toISOString(). (Edited; previously stated that the toString method implementations are different which isn't true).

    In both Chrome (Thu Oct 01 2015 00:00:00 GMT+0200) and Firefox (Date 2015-09-30T22:00:00.000Z) methods like .getDate() and .getMonth() return the same values (1 and 9 respectively). The Date objects are the same.

提交回复
热议问题