Using jQuery: Get Current Year

Using jQuery to output the current year is a useful substitute when your website pages are done in HTML and not with server side languages like PHP or ASP. The following code demonstrates how to print the current year in HTML using jQuery.

First, you will need to reference a jQuery library in the <head> of your HTML. You can do this one of two ways:

  • Link directly to the jQuery library on the jQuery code site
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
  • Download a version of jQuery from the jQuery site (http://jquery.com/) and relatively link to it from within your site
<script src="/script/jquery-1.4.2.min.js" type="text/javascript"></script>

With the jQuery library referenced you can now pull the current year and push it to an HTML element using some jQuery syntax. The below JavaScript grabs the current year and pushes the value to the “text” of the HTML element with the ID of “year”.

<script type="text/javascript">
  var currentYear = (new Date).getFullYear();
  $(document).ready(function() {
  $("#year").text( (new Date).getFullYear() );
  });
</script>

Now we create the HTML element to receive the year value:

<p>Copyright <span id="year">TEXT</span> Company Name - All Rights Reserved.</p>

With this code in place, the year will be pushed to the TEXT position of the “year” span tag when the DOM is ready. This functionality is useful for elements such as copyright dates or other date representations that need to stay current.

Want to learn more about jquery? Try this resource...

jQuery: Novice to Ninja
  • Tim

    Many thanks – really useful!  Easier than sticking in a php call  😉

    • eppand

      Tim, glad you found it helpful!

  • yoda

    It took me forever to try and get it to work, but then i realized i needed to link the jquery in its own script tag. And then have a separate script tag for the javascript. Thanks!

  • Jes

    This was helpful – i didn’t know how to get the year with jQuery!

    Small note: It seemed to me you should be either using the variable “currentYear” (defined in line 2) on line 4 when you’re doing the text injection, or else you should remove the variable entirely since you’re using the full contents of that variable inside the injection. Right now it’s redundant. This is the modification I used:

    var currentYear = (new Date).getFullYear();
    $(document).ready(function() {
    $(“#year”).text(currentYear);
    });

    Thanks again for the tip!

  • Nick Balcombe

    Thank you very much!

  • anotherarc

    Doesn’t seem to work in IE??

  • Lahiru SupunChandra.

    Ha ha ha…. Awesome Work Buddy… Thank You Very Much…Keep it up….