how to get current year in javascript

How to Get Current Year in Javascript

If you are working on a web application or website, sometimes you may need to get the current year using Javascript. There are several ways to do so, and in this article, we will explore some of the best ways.

Method 1: Using Date Object

The easiest way to get the current year in Javascript is by using the Date object. The Date object provides several methods that allow us to get the current date and time, including the year.

const currentDate = new Date();
const currentYear = currentDate.getFullYear();

The code above creates a new Date object and assigns it to the currentDate variable. Then we use the getFullYear() method to get the current year and assign it to the currentYear variable.

Method 2: Using new Date().toLocaleString()

If you want to get the current year in a specific format, you can use the toLocaleString() method. This method converts a Date object to a string, using the specified locale and formatting options.

const currentDate = new Date();
const currentYear = new Date(currentDate).toLocaleString('en-US', {year: 'numeric'});

The code above creates a new Date object and assigns it to the currentDate variable. Then we create a new Date object from the currentDate object and use the toLocaleString() method to format the date as a string with only the year. The 'en-US' argument specifies the locale, and the {year: 'numeric'} argument specifies that we only want the year.

Method 3: Using new Intl.DateTimeFormat()

Another way to get the current year in a specific format is by using the Intl.DateTimeFormat() method. This method creates a formatter object that can format dates and times, including the year.

const currentDate = new Date();
const formatter = new Intl.DateTimeFormat('en', {year: 'numeric'});
const currentYear = formatter.format(currentDate);

The code above creates a new Date object and assigns it to the currentDate variable. Then we create a new DateTimeFormat object with the 'en' locale and {year: 'numeric'} options, which specifies that we only want the year. Finally, we use the format() method of the formatter object to format the date as a string with only the year.

Conclusion

Getting the current year in Javascript is easy, and there are several ways to do so. Using the Date object is the easiest and most straightforward way, while using toLocaleString() and Intl.DateTimeFormat() methods allows you to format the date in a specific way.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe