Javascript getYear fix

The Javascript Date object method getYear() will return a 2, 3 or 4 digit value depending on the actual year specified and the browser version used. This post looks at two solutions for this Javascript getYear() issue.

The Javascript below will set month as an integer value between 0 (January) and 11 (December), day as an integer value between 1 and 31, and year to the current year.

var mydate = new Date();
var month = mydate.getMonth();
var day = mydate.getDate();
var year = mydate.getYear();

The issue with the Javascript getYear() method is that for some dates and browser versions for dates prior to 2000 it may return either a 2 digit year or 4 digit year, and for dates since 2000 an integer value with 2 3 or 4 digits. The three digit ones would, for example be 108 for the year 2008.

The first solution is to test if the year is less than 2000 and if so add 1900 to it like so:

if(year < 2000) year += 1900;

The second solution is to use the newer getFullDate() method which always returns a 4 digit year.

var year = mydate.getFullYear();

Support for this method arrived in Javascript 1.3 which means (using the information from my “Which browsers support which versions of Javascript” post) all versions of Firefox, Opera from version 7.0 (and possibly earlier) and Internet Explorer from version 4.