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

后端 未结 2 901
爱一瞬间的悲伤
爱一瞬间的悲伤 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:19

    I have found the string format that works for most browsers is the following.

    stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
    date = new Date(stringFormat);
    

    I use moment.js to provide even further compatibility, so far this works well for IE9+, Chrome and Firefox. But took me many several forums and other responses in SOF to find a good solution.

    The biggest issue is being compatible with older browsers, locale formats, etc. For example this one was almost correct, but the I found that IE9 doesn't like .sss (miliseconds) and wasn't working either. Firefox had errors with european Date formats too.

    Does anyone have a better way to deal with this? Please share the knowledge! :)

提交回复
热议问题