使用不同浏览器的 JavaScript 中的日期格式问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3566125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:32:11  来源:igfitidea点击:

Problem with date formats in JavaScript with different browsers

javascriptdatetimedate-formatdate-parsing

提问by TimS

I am working with dates in an RSS feed, but am finding differing results when using the code below in IE, Chrome and Firefox:

我正在处理 RSS 提要中的日期,但在 IE、Chrome 和 Firefox 中使用以下代码时发现不同的结果:

new Date('2001-01-01T12:00:00Z')

Firefox is happy with that, but Chrome and IE return Invalid Date.

Firefox 对此很满意,但 Chrome 和 IE 返回无效日期。

I thought I'd try replacing the T and Z as follows:

我想我会尝试替换 T 和 Z 如下:

new Date('2001-01-01 12:00:00')

This time Chrome is happy with that, but Firefox and IE return Invalid Date.

这一次 Chrome 对此很满意,但 Firefox 和 IE 返回无效日期。

Any ideas what I should do to get a date object in all browsers with this format?!

任何想法我应该怎么做才能在所有浏览器中使用这种格式获取日期对象?!

Many thanks, Tim

非常感谢,蒂姆

回答by mplungjan

This works in all browsers on my box - try it in the console:

这适用于我机器上的所有浏览器 - 在控制台中尝试:

alert(new Date('2001/01/31 12:00:00'))

so

所以

new Date('2001-01-01T12:00:00Z'.replace(/\-/g,'\/').replace(/[T|Z]/g,' '))

IE8, FF3.6, Safari4, Chrome

IE8、FF3.6、Safari4、Chrome

回答by NicolasT

Can you try:

你能试一下吗:

new Date(2001,0,1,12,0,0)

This means:

这意味着:

new Date(year,month,day,hour,minutes,seconds) 

回答by theycallmemorty

You could also try using Date.js- an open source javascript date manipulation library.

您也可以尝试使用Date.js- 一个开源的 javascript 日期操作库。

回答by PleaseStand

This works on all of the major 5 browsers and causes all browsers to recognize the time as GMT/UTC rather than local time (the Z suffix means the time is UTC):

这适用于所有主要 5 浏览器,并导致所有浏览器将时间识别为 GMT/UTC 而不是本地时间(Z 后缀表示时间是 UTC):

new Date('2001-01-01T12:00:00Z'.replace(/\-/g,'\/').replace(/T/,' ').replace(/Z/,' -0'))

I thank mplungjan for his answer.

我感谢 mplungjan 的回答。