Correct for 2-digit date entry in Javascript

In working with the function described in the last post, I realized that I needed some way to correct the year when a user entered a 2-digit year as opposed to a 4-digit year. This is because Javascript interprets ‘3/1/09’ as ‘March 1, 1909’ — throwing off my calculations quite alarmingly. There are a variety of fixes for this posted online, but most of them are focused on 19xx and 20xx. And even though it seems unlikely that anyone will be using anything I’ve written in 21xx, I still wanted to plan for it – wanted to learn from my y2k forebears.

So I worked out a script that subtracts the first two numbers of the entered year from the first two numbers of the current one, multiplies the result by 100 and then adds it to the entered year. Thus, if the current year is 2008 and the entered year is 1909, the script does this:

  • 20 – 19 = 1
  • 1 * 100 = 100
  • 1909 + 100 = 2009

If the current year is 2008 and the entered year is 2009, the script does this:

  • 20 – 20 = 0
  • 0 * 100 = 0
  • 2009 + 0 = 2009

And, if someone is still using my script in 2108, and javascript still interprets a 2-digit year of ’09 as 1909, the script would work like this:

  • 21 – 19 = 2
  • 2 * 100 = 200
  • 1909 + 200 = 2109

Here’s the script:

function correctYear(dt)
{
//get current date
var currDate = new Date();

//get full year for current date and arg date and convert to string
var dtYear = dt.getFullYear() + “”;
var currYear = currDate.getFullYear() + “”;

//subtract first two numbers of arg year from first two numbers of current year
var diff = (Number(currYear.substring(0,2)) – Number(dtYear.substring(0,2)));

//multiply difference by 100 and add to arg year
dtYear = Number(dtYear) + (diff * 100);

//set corrected year as arg date year, and return corrected date object
dt.setFullYear(dtYear);
return dt;
}

It’s not perfect – if the someone in 2108 really meant 2009, not 2109, then they’ll have to type that out. Same for someone in 2098 referring to 2102 – if they type in ’02, my script will interpret that as 2002 (of course, once the century turns, it’s all good again). But I took my shot. You can see the function in action in my last post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s