Javascript Safari JS 无法解析 YYYY-MM-DD 日期格式?

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

Safari JS cannot parse YYYY-MM-DD date format?

javascriptvalidationdatetimesafari

提问by Austin Hyde

In a project I am working on, I need to validate a date entered into an <input type="date">

在我正在进行的项目中,我需要验证输入到 <input type="date">

With Safari 4/5 (on Mac OSX) the Javascript fails to parse dates of the format YYYY-MM-DD, returning NaNinstead of the expected epoch timestamp.

使用 Safari 4/5(在 Mac OSX 上),Javascript 无法解析格式的日期YYYY-MM-DDNaN而是返回预期的纪元时间戳。

I am using the following technique to validate the field just before the form is submitted:

我正在使用以下技术在提交表单之前验证该字段:

//value = '2010-06-21'
var stamp = Date.parse(value);
if (isNaN(stamp)) {
    //notify user
} else {
    value = new Date(stamp).format_mysql();
}

Where format_mysql()is a prototype function that formats the date (correctly) into MySQL Date-Time format (YYYY-MM-DD).

哪里format_mysql()是将日期(正确)格式化为 MySQL 日期时间格式 (YYYY-MM-DD) 的原型函数。

Replacing the -'s with /'s (YYYY/MM/DD) yields a "correct" timestamp.

-/'s (YYYY/MM/DD)替换's 会产生一个“正确”的时间戳。

I should note that the field should accept any date format, not just YYYY-MM-DD, and that though I would like to, I cannot use libraries like Date.js

我应该注意到该字段应该接受任何日期格式,而不仅仅是 YYYY-MM-DD,尽管我愿意,但我不能使用像 Date.js 这样的库

How can I fix this, or is there a better way to parse/validate a date?

我该如何解决这个问题,或者有没有更好的方法来解析/验证日期?

回答by CMS

The behavior of the Date.parsemethod is implementation dependent, on ECMAScript 5, this method can parse ISO8601 formatted dates, but I would recommend you to make the parsing manually.

Date.parse方法的行为取决于实现,在 ECMAScript 5 上,此方法可以解析 ISO8601 格式的日期,但我建议您手动进行解析。

Some time ago I've made a simple function, that can handle a format specifier argument:

前段时间我做了一个简单的函数,它可以处理格式说明符参数:

function parseDate(input, format) {
  format = format || 'yyyy-mm-dd'; // default format
  var parts = input.match(/(\d+)/g), 
      i = 0, fmt = {};
  // extract date-part indexes from the format
  format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; });

  return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]);
}

parseDate('06.21.2010', 'mm.dd.yyyy');
parseDate('21.06.2010', 'dd.mm.yyyy');
parseDate('2010/06/21', 'yyyy/mm/dd');
parseDate('2010-06-21');

Also you could detect the ECMAScript 5 behavior to parse ISO formatted dates, you can check if the Date.prototype.toISOStringis available, e.g.:

您也可以检测 ECMAScript 5 行为来解析 ISO 格式的日期,您可以检查它Date.prototype.toISOString是否可用,例如:

if (typeof Date.prototype.toISOString == "function") {
  // ES5 ISO date parsing available
}

回答by Vishnu Vardhana

Generally DD-MM-YYYY format is not support in safari.

safari 中一般不支持 DD-MM-YYYY 格式。

value = 2010/06/21 ; //should work.

值 = 2010/06/21 ;//应该管用。

(or)

(或者)

value = new Date('2010-06-21'.replace(/-/g, "/"));

value = new Date('2010-06-21'.replace(/-/g, "/"));

回答by tc.

the field should accept any date format

该字段应接受任何日期格式

You don't mean what you think you mean.

你的意思不是你认为的意思。

  • It's difficult to reliably distinguish between M/D/Y (US) and D/M/Y (UK). D.M.Y is more common in the UK, but by no means universal.
  • Good luck with dates before around 1600 — the Gregorian (solar) calendar was introduced in 1582, and was only (mostly universally) adopted in the 20th century (Wikipedia gives 1929). February 30 was a valid date Sweden.
  • OS X gives you a choice of 13 (!) calendars, though the default is Gregorian.
  • 很难可靠地区分 M/D/Y(美国)和 D/M/Y(英国)。DMY 在英国更常见,但绝不是普遍的。
  • 祝 1600 年之前的日期好运——公历(太阳历)于 1582 年引入,并且仅(大部分普遍)在 20 世纪采用(维基百科给出了 1929 年)。2 月 30 日是瑞典的有效日期。
  • OS X 为您提供了 13 个 (!) 日历选择,但默认是公历。

Instead, I recommend using a calendar widget. I think JQuery has one, but ICBW.

相反,我建议使用日历小部件。我认为 JQuery 有一个,但 ICBW。

回答by kennebec

You can get an unambiguous date from input, but you still need to check it, so a user doesn't give you April 31.

你可以从输入中得到一个明确的日期,但你仍然需要检查它,所以用户不会给你 4 月 31 日。

<fieldset id= "localdate"> 
<select id= "monthselect" size= "1"> 
<option selected= "selected"> January</option> 
<option> February</option> 
<option> March</option> 
<option> April</option> 
<option> May</option> 
<option> June</option> 
<option> July</option> 
<option> August</option> 
<option> September</option> 
<option> October</option> 
<option> November</option> 
<option> December</option> 
</select> 
<label> Date: <input name= "inputdate" size= "2" value= "1"> </label> 
<label> Year: <input name= "inputyear" size= "4" value= "2010"> </label> 
</fieldset> 

shortcut for document.getElementsByName

document.getElementsByName 的快捷方式

function byName(s, n){ n= n || 0; return document.getElementsByName(s)[n]; }

function byName(s, n){ n= n || 0; 返回 document.getElementsByName(s)[n]; }

function getDateInput(){
    var day, y= parseInt(byName('inputyear').value),
    m= byName('monthselect').selectedIndex,
    d= parseInt(byName('inputdate').value);

    if(!y || y<1000 || y> 3000) throw 'Bad Year '+y;
    if((!d || d<1 || d> 32) throw 'Bad Date '+d;
    day= new Date(y,m,d);
    if(day.getDate()!= d) throw 'Bad Date '+d;
    value= day.format_mysql();
}

you can preset the fields to reflect the current date onload

您可以预设字段以反映当前的加载日期

onload= function(){
    var now= new Date();
    byName('inputyear').value= now.getFullYear();
    byName('monthselect').selectedIndex= now.getMonth();
    byName('inputdate').value= now.getDate();
}