Date.js parseExact() not parsing 4 digit years whe

2019-06-26 03:42发布

问题:

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

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:

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?

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"));
     });

});

回答1:

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

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/