OneBite.Dev - Coding blog in a bite size

get current year in javascript

Code snippet for how to how to get current year in javascript with sample and detail explanation

In this article, we’ll walk you through a straightforward and easy-to-follow guide on how to get the current year in JavaScript - one of the most popular programming languages in use today. Understanding how to manipulate date and time is a fundamental part of programming, and here we’ll focus specifically on obtaining the current year.

Code snippet to get current year in JavaScript

The following code snippet gives you the necessary method:

var today = new Date();
var year = today.getFullYear();
console.log(year);

With this simple JavaScript code, you can get the current year and display it in the console.

Code Explanation for getting the current year in JavaScript

Let’s dissect this simple code snippet step by step:

  1. var today = new Date(); : You start by creating a new Date object. The Date object is a built-in JavaScript object. It allows you to work with dates and times. Here, ‘today’ is the variable declared to hold the Date object. By calling the Date object with the ‘new’ keyword but without any argument, it gives you the current date and time.

  2. var year = today.getFullYear(); : The getFullYear() method is called on the ‘today’ variable. This method, as the name suggests, allows you to get the four-digit year of any date object.

  3. console.log(year); : Finally, ‘console.log(year);’ will display the current year in your console.

Now you have successfully gotten the current year using JavaScript. This method can be extremely useful in various situations such as dynamically updating copyright notices, generating reports based on the current year, or simply displaying the current year on your website.

javascript