jQuery Snippets: Getting the Current Year

Here's a fun, simple, and incredibly useful jQuery that you can probably use on just about every single one of your projects. This snippet uses jQuery to grab the current year and display it wherever you'd like within your webpage. This is a great chunk of code to have on hand.

One particularly good use for this snippet is in the copyright section of your web page or project. Most websites have a copyright notice, followed by the current year, somewhere on their web pages (usually you'll find it down towards the footer or in the footer, but not always).

We've all probably seen sites with copyrights that are super outdated. When you see a copyright date from a few years prior, chances are that the website owners hard-coded the date into their HTML, which is alright, if you are capable of or can remember to change the copyright date every single year. Most people, it's probably safe to assume, would rather not have to worry about it. That's where jQuery comes in.

With the following jQuery snippet, the current year is grabbed and loaded each and every time the page loads, so your users will never be looking at an outdated copyright that is boasting the wrong year. Take a look at the snippet below so you can use it for yourself on your future and current projects:

$(function () {
 thisyear = new Date().getFullYear();
 $('.currentyear').text(thisyear);
});

The snippet above is super straightforward. It uses the .getFullYear() method to grab the current full year (so for example, 2017 instead of '17) and then it uses the .text() method to add the year to the HTML element that has the .currentyear class tag by passing the "thisyear" variable through the .text() method. Easy as pie. For an example of the HTML that might accompany this jQuery to display your copyright year, take a look at the snippet below:

<p>© <span class=".currentyear"></span></p>

When used with the jQuery snippet in this tutorial, the current year will be dynamically added within those span tags, and you'll never have to spare another thought for your copyright line again.



Responsive Menu
Add more content here...