...

View Full Version : Formatting two digit years.



nlkflynn
07-11-2006, 01:24 AM
Formatting two digit years.
Hello,
I m developing an app and one of the requirements is that dates that are entered with two digit years should be formatted to four digit years and it be in this century, so 01/01/01 would become 01/01/2001. I tried the getFullYear() function but it defaults 01 to 1901. Is there something else I can use?

Thanks

Philip M
07-11-2006, 08:24 AM
Try adding 100 to 1901 to get 2001.

var now = new Date();
var yynow = now.getYear(); // IE returns 2006. Netscape and Opera return 106.

nlkflynn
07-11-2006, 12:33 PM
Thanks,
I'm not sure that will work, I probably didn't explain myself too clearly in my post. The user will be able to enter any date, so it could be a 2 digit year or 4 digit year. If it's a four digit year we are leaving it be. I guess the problem I'm having is how to know when they've entered a two digit or four digit year. In my code
I'm just creating a date object and then getting the month, day, year from that.

Thanks

vwphillips
07-11-2006, 01:17 PM
Select Lists are the only way to be sure but


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script language="JavaScript" type="text/javascript">
/*<![CDATA[*/

function CkYear(obj){
var val =obj.value.split('/');
if (val.length!=3){ alert('incorrect format'); return; }
for (var zxc0=0;zxc0<val.length;zxc0++){
if (isNaN(val[zxc0])){
alert('incorrect format'); return;
}
}
if (val[2].length==2){
val[2]='20'+val[2];
}
if (val[2].length!=4){
alert('incorrect year format'); return;
}
if (val[1]<1||val[1]>12){
alert('incorrect month format'); return;
}
if (val[0]<1||val[0]>zxcDinM(val[2],val[1])){
alert('incorrect day format'); return;
}
obj.value=val.join('/');
}

function zxcDinM(zxcyr,zxcm){
return new Date(zxcyr,zxcm,1,-1).getDate();
}


/*]]>*/
</script>
</head>

<body>
<input value="01/02/2001" onblur="CkYear(this);" >
</body>

</html>

see also

http://www.vicsjavascripts.org.uk/FormCompendium/FormCompendium.htm#f14

nlkflynn
07-11-2006, 01:34 PM
Great,
Thanks for all the help



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum