JavaScript new Date(string) compatible for most browsers (Dec 2016)

后端 未结 2 874
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 02:34

I\'ve been dealing with this annoying bug when creating a new Date(string) in JavaScript. My question is, has anyone found a better/more standardized solution for this issue tha

2条回答
  •  遥遥无期
    2021-01-27 03:16

    According to MDN:

    Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

    The same applies to Date.parse(). If you fear such inconsistencies (because your browser support is very extensive, or because you handle data from external sources), you can always use the full constructor:

    new Date(year, month, [day, hour, minute, second, millisecond])
    

    The parameters between brackets are optional. If you can parse the date using a reliable tool (such as moment.js, as you mentioned), you can then build a native Date with no danger using this.

    It's cumbersome, but pack it into a function and never look at it again.

提交回复
热议问题