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?
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.
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).
The getYear() method returns the year in the specified date according to local time.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With