Monday, December 04, 2006

Show the Current Year with Javascript

On a flat HTML site I was working on over the weekend, I had a need to display the current year for copyright information (You know, 'Copyright 2006'). I didn't want to hardcode '2006' in there, and in this instance I was stuck using static HTML, so no ASP or PHP. Javascript was the obvious choice.

I'm not an expert JavaScripter, but I thought this could be done in a single line of code like:

document.write(date.Year());

Not so. I quickly realized you need to instantiate the Date object, and get the current date from that. So my code now was this:

var time = new Date();
document.write(time.getYear());


I found the above code referenced on a few websites and it worked fine in IE6 and IE7. However, when I tested in Firefox and Safari, the year showed as '106'.

A little more Googling and I found that I needed to call the 'getFullYear()' property of the Date object. So my current code, which works in all the browsers I was able to test with is:

var time = new Date();
document.write(time.getFullYear());

No comments: