Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript evaluate a 2-digit year of 00 as 1900 instead of 2000?

Tags:

I have an old web app where Javascript is used to validate some dates. Users usually use 2-digit years and I recently discovered it was evaluating 00 as 1900 instead of 2000

if (new Date(tb[0].value) > new Date(tb[1].value)){     alert('Starting date must come before the ending date');     tb[0].focus();     return false; } 

Entering 1/1/99 in the first box and 1/1/00 in the 2nd will cause an error message saying the start date has to be before the end date because 99 is evaluating at 1999 while 00 is evaluating at 1900.

Of course, Users can get around this using 4-digit years, but I still want to know what can be done to get Javascript to evaluate 2-digit years correctly.

So my question is, how can I get Javascript to evaluate 00 as 2000 and not 1900?

like image 409
Rachel Avatar asked Dec 30 '11 16:12

Rachel


People also ask

What does 2 digit year mean?

If a data item with a 4-digit year or century is moved to a 2-digit year, the first 2 digits of the year (the century) are truncated.

What is Date in JavaScript?

A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since the ECMAScript epoch, which is defined as January 1, 1970, UTC (equivalent to the UNIX epoch).

Which method is used to get the year of a Date object in YYYY format in JavaScript?

The getYear() method returns the year in the specified date according to local time.

What is new Date () in JavaScript?

It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.


2 Answers

The simplest way is just to accept it does it that way and check for it.

if (date.getFullYear() < 1970) {     date.setFullYear(date.getFullYear() + 100); } 

1970 is of course just an example value as you have to have a sensible break point. You may want to do that as current year - x instead of a constant of course.

like image 191
Thor84no Avatar answered Oct 07 '22 00:10

Thor84no


It does that because the language was created in the 1990's (and in a hurry). You can use getFullYear() and setFullYear() to handle years in a non-goofy way.

What I've done is write some code to check for year values less than 100, and if it's greater than 90 (or something similarly appropriate, depending on the situation) assume it's in the 20th century, otherwise assume the 21st.

And @Rachel no there's no way to tell the runtime library to behave differently, at least not any standardized way. That's just how the Date code works.

like image 20
Pointy Avatar answered Oct 07 '22 01:10

Pointy