In this blog post, I will show you how to get the current year using JavaScript. This can be useful for a
variety of purposes, such as displaying the current year in the copyright notice of your website or for
performing calculations involving the current date. With just a few lines of code, you’ll be able to display
the current year on your website with ease.
Getting the Current Year
To get the current year in JavaScript, you will need to create a new Date object, which will
contain the current date and time by default. The Date object provides a method called
getFullYear(), which returns the four-digit year value of the date.
Here is an example of how to get the current year in JavaScript:
[sourcecode language=”javascript”]
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
console.log(currentYear);
[/sourcecode]
In this example, we first create a new Date object called currentDate. We
then use the getFullYear() method to get the current year, which we store in the variable
currentYear. Finally, we log the current year to the console.
Displaying the Current Year on Your Website
Now that you know how to get the current year in JavaScript, you can use it to display the current year on
your website. For example, you could update the copyright notice in your website’s footer to include the
current year.
Here’s an example of how to display the current year on your website using JavaScript:
HTML:
[sourcecode language=”html”]
[/sourcecode]
JavaScript (script.js):
[sourcecode language=”javascript”]
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
document.getElementById(‘currentYear’).textContent = currentYear;
[/sourcecode]
In this example, we first create an HTML file with a footer containing a span element with
the ID currentYear. This is where the current year will be displayed. Then, we create a
separate JavaScript file called script.js and include it in the HTML file using a
script tag. In the JavaScript file, we use the same technique as before to get the current
year, and then we update the textContent of the span element with the ID
currentYear to display the current year on the page.
Conclusion
Getting the current year in JavaScript is a simple task that can be accomplished with just a few lines of code.
By using the Date object and its getFullYear() method, you can easily display
the current year on your website or use it for other purposes in your application. Happy coding!