new Date() 在 Safari 中使用 Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4622732/
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-08-23 13:19:08  来源:igfitidea点击:

new Date() using Javascript in Safari

javascriptjquerydatesafarinew-operator

提问by Dodinas

I'm having an issue using the new Date() function in Javascript. Safari is giving me an "Invalid Date" message.

我在 Javascript 中使用新的 Date() 函数时遇到问题。Safari 给我一条“无效日期”消息。

I've created a short example at jsbin.

我在jsbin创建了一个简短的例子。

This appears to work on all other browsers, but not Safari. Any ideas on how I can take the value from an input (such as 2011-01-03) and turn it into a date object, while having it work properly in Safari?

这似乎适用于所有其他浏览器,但不适用于 Safari。关于如何从输入(例如 2011-01-03)中获取值并将其转换为日期对象,同时使其在 Safari 中正常工作的任何想法?

Many thanks!

非常感谢!

回答by CMS

The date parsing behavior on JavaScript is implementation-dependent, the ISO8601 format was recently added to the ECMAScript 5th Edition Specification, but this is not yet supported by all implementations.

JavaScript 上的日期解析行为取决于实现,最近将 ISO8601 格式添加到 ECMAScript 第 5 版规范中,但并非所有实现都支持这种格式。

I would recommend you to parse it manually, for example:

我建议您手动解析它,例如:

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  return new Date(parts[0], parts[1]-1, parts[2]);
}

parseDate('2011-01-03'); // Mon Jan 03 2011 00:00:00

Basically the above function matches each date part and uses the Date constructor, to build a date object, note that the monthsargument needs to be 0-based (0=Jan, 1=Feb,...11=Dec).

基本上,上面的函数匹配每个日期部分并使用 Date 构造函数来构建日期对象,请注意参数需要基于0 (0=Jan, 1=Feb,...11=Dec)

回答by i.AsifNoor

The easy solution I tried Download date.js from http://datejs.com/Include in your file

我尝试过的简单解决方案 从http://datejs.com/下载 date.js 包含在您的文件中

then var date = Date.parse('1970-01-12 00:00:00'); var formattedDate = date.toString('yyyy-MM-dd');

然后 var date = Date.parse('1970-01-12 00:00:00'); var formattedDate = date.toString('yyyy-MM-dd');

回答by n0nick

While @CMS's solution is probably superior, I found that using Date.parse('2011-01-13')is also a quick, working solution.

虽然@CMS 的解决方案可能更胜一筹,但我发现使用Date.parse('2011-01-13')也是一种快速有效的解决方案。

回答by ??α??

csnover has some progressive ISO 8601 Date enhancement code available on GitHub: https://github.com/csnover/js-iso8601/blob/master/iso8601.js

csnover 在 GitHub 上提供了一些渐进式 ISO 8601 日期增强代码:https: //github.com/csnover/js-iso8601/blob/master/iso8601.js

Including his code should provide a temporary fix while the Safari team work toward a more complete ES5 implementation.

在 Safari 团队努力实现更完整的 ES5 实现时,包含他的代码应该会提供一个临时修复。