How to make javascript Date.parse understand short years?

I noticed that Date.Parse cannot handle only two digits.

Say I have it

 mm/dd/yy = 7/11/20 

The date syntax will look like this: = 7/11/1920 . Can you set it to use the two thousandth year? As if this is strange, I got a jquery ui date picker, and if you type 7/11/20 , then it turns out 2020 .

So, it would be nice if Date.Parse could hold on, I would prefer that both of them do not know what is happening, or both know what is happening, then there is one that knows and one that doesn't.

+6
javascript jquery-ui datepicker
source share
4 answers

Not that I knew. But you can always set the year:

 YourDate="7/11/20"; DateObj=new Date(YourDate.replace(/(\d\d)$/,"20$1")); alert(DateObj); 

This code is in action.

Edit: The following code will handle both full and short years:

 YourDate="7/11/2020"; DateObj=new Date(YourDate.replace(/\/(\d\d)$/,"/20$1")); alert(DateObj); 

This code is in action.

+5
source share

So your question is, can you change the way Date.parse works so that low-double-digit dates are interpreted as dates after 2000?

Yes, it can be done, just a Date.parse shadow with your own parsing function.

 // don't do this! Date.parse = function (str) { /* your parse routine here */ } 

Of course, this is a very bad idea for shadow properties (including β€œmethods” or function properties) of host objects, because this will lead to incorrect behavior in other scripts that expect these properties to work in a certain way.

It is also a bad idea to use double-digit dates, but this may not be under your control. If this does not go beyond your control, I would advise you to simply forget the 2-digit dates and use the value of the whole year.

0
source share

Here is my solution:

 function parseDate(stringValue) { var date = new Date(stringValue); if (!isNaN(date.getTime())) { // if they typed the year in full then the parsed date will have the correct year, // if they only typed 2 digits, add 100 years to it so that it gets translated to this century if (stringValue.indexOf(date.getFullYear()) == -1) { date.setFullYear(date.getFullYear() + 100); } return date; } else { return null; } } 
0
source share

How about this?

 var date = '7/11/20'; var idx = date.lastIndexOf('/') + 1; date = date.substr(0,idx) + '20' + date.substr(idx); var result = Date.parse(date);​ alert(result); 

or this version, which will first check the YYYY format.

 var date = '7/11/2020'; var idx = date.lastIndexOf('/') + 1; if(date.substr(idx).length < 4) { date = date.substr(0,idx) + '20' + date.substr(idx); } var result = Date.parse(date); alert(new Date(result))​;​ 
-one
source share

All Articles