javascript Date.js parseExact() 在作为数组传入时不解析 4 位年份

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

Date.js parseExact() not parsing 4 digit years when passed in as an array

javascriptjquerydatejs

提问by seanicus

Am I missing something with Date.parseExact() in date.js? According to the api documentation, I should be able to do this:

我是否在 date.js 中遗漏了 Date.parseExact() 的某些内容?根据 api 文档,我应该能够做到这一点:

Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]); // The Date of 15-Oct-2004

That is, I should be able to pass in a string array which contains "...the expected format {String} or an array of expected formats {Array} of the date string." However, when I do this:

也就是说,我应该能够传入一个字符串数组,其中包含“......日期字符串的预期格式 {String} 或预期格式 {Array} 的数组”。但是,当我这样做时:

var d = Date.parseExact($(this).val(), ["MMddyy", "Mddyyyy", "MM/dd/yy","MM/dd/yyyy"])

I get back nulls for dates containing 4 digit years (that is, matching the MMddyyyy and MM/dd/yyyy formats). Am I missing something or is this a bug in Date.js?

对于包含 4 位年份的日期(即匹配 MMddyyyy 和 MM/dd/yyyy 格式),我会返回空值。我是否遗漏了什么或者这是 Date.js 中的错误?

Here is the complete block of code, for context:

这是完整的代码块,用于上下文:

$(function () {
     $('#FCSaleDate').change(function (e) {
         var d = Date.parseExact($(this).val(), ["MMddyy", "MMddyyyy", "MM/dd/yy","MM/dd/yyyy"])
         alert(d.toString("MM/dd/yyyy"));
     });

});

回答by Blazemonger

It appears date.js is attempting to parse the four-digit year as a two-digit year, failing, and returning null on failure.

看来 date.js 试图将四位数年份解析为两位数年份,失败并在失败时返回 null。

To prevent this, switch your masks around so it tries the four-digit masks first:

为防止这种情况发生,请切换您的掩码,使其首先尝试四位数掩码:

$(function () {
     $('#FCSaleDate').change(function (e) {
         var d = Date.parseExact($(this).val(),["MMddyyyy","MMddyy","M/d/yyyy","M/d/yy"]);
         alert(d.toString("MM/dd/yyyy"));
     });

});

http://jsfiddle.net/mblase75/ttEqh/1/

http://jsfiddle.net/mblase75/ttEqh/1/