← coderrocketfuel.com

Get The Current Year Using Node.js

How do you get the current year using Node.js?

You can get that information by using the Node.js Date object. Specifically, you can use the new Date().getFullYear() method to return the four-digit year in a YYYY format.

The new Date() method gets today's date:

const todaysDate = new Date()
// 2022-05-15T07:11:20.082Z

The todaysDate variable will have a value similar to the one shown above depending on the current date.

Using that variable, we can get the current year:

const todaysDate = new Date()
const currentYear = todaysDate.getFullYear()
// 2022

As shown above, the currentYear will hold the value for the current year in a YYYY format.

You can also combine the two variables shown above to be more succinct:

const currentYear = new Date().getFullYear()
// 2022

There you have it! That's how you get the current year in Node.js using the Date object and the getFullYear() method.

Thanks for reading and happy coding!