开发者

How to make javascript Date.parse understand short years?

I noticed Date.Parse can't handle only 2 digits dates.

Say I have this

mm/dd/yy = 7/11/20

Date parse will think it is = 7/11/1920. Can you set it to use the year two thousand? Like it's kinda weird I got the jquery u.i date picker and if you type in 7/11/20 it will figure out 2020.

So it would be nice if Date.parse could keep up I rather have them both not know what is going on or both know what is going on then have开发者_如何学Go one that knows and one that does not know.


Not that I'm aware of. But you can always adjust the year:

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

alert(DateObj);

This code 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 in action.


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

Yes, it can be done, simply shadow Date.parse with your own parse function.

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

Of course, it's generally a very bad idea to shadow properties (including 'methods' aka function properties) of host objects, because it will cause incorrect behavior in other scripts that expect those properties to work a certain way.

It's also a bad idea to use two digit dates, but that might be beyond your control. If it's not beyond your control, I'd advise to just forget 2-digit dates and use the full year value instead.


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


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 that will test for a YYYY format first.

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))​;​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜