将2位数日期转换(格式化)为4位数日期

将2位数日期转换(格式化)为4位数日期

问题描述:

我无法将2位数日期格式化为4位数日期。

I'm having trouble properly formatting 2-digit dates as 4-digit dates.

我有一个文本输入字段:

I have a text input field:

<input type="text" value="" class="date"/>

然后我想在用户输入后以mm / dd / yyyy格式对其进行格式化一个约会。所以我有一个onChange事件:

And then I want to format it in the "mm/dd/yyyy" format after the user enters a date. So I have an onChange event:

$('.date').on('change',function(){
    var date = new Date($(this).val());
    $(this).val((date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear());
});

好的,现在是奇怪的事情(我将以12/12/12为例) date):

Okay, so now comes the oddities (I'll be using 12/12/12 as an example date):

1)getFullYear()在所有IE,FF中返回1912。 Chrome返回2012.

1) getFullYear() returns 1912 in all IE, FF. Chrome returns 2012.

2)getYear()在IE,Chrome中返回112。 FF返回12.

2) getYear() returns 112 in IE, Chrome. FF returns 12.

因此,此时似乎唯一的选择是嗅探用户代理,并相应地使用它。反正在嗅探UA吗?

So it seems like the only option at this point is to sniff the user agent, and use that accordingly. Is there anyway around sniffing the UA?

你可以先试着分开输入部分

you can try,first, to seperate the parts of the input

...
var input=$(this).val();
var month=input.substr(0,2)-1;
var day=input.substr(3,2);
var year=parseInt("20"+ input.substr(6,2));

然后启动一个新的Date对象:

and then initate a new Date object:

var date= new Date(year,month,day);

或将其写回现场,如下所示:

or write it back to the field, as you did:

$(this).val((date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear());