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

只谈情不闲聊 提交于 2019-12-12 12:17:40

问题


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/



来源:https://stackoverflow.com/questions/8567476/date-js-parseexact-not-parsing-4-digit-years-when-passed-in-as-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!