将2位数日期转换(格式化)为4位数日期 [英] Converting (formatting) 2-digit date to a 4-digit date

查看:131
本文介绍了将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());

这篇关于将2位数日期转换(格式化)为4位数日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆