How to get current year - JavaScript

Mo Ibra

Mo Ibra

Jan 1, 2023

In this article we will learn how to get current year in JavaScript.

It is very common to get current year in JavaScript in JavaScript.


Problem

Now we have a problem, which is that we want to get current year in JavaScript.


Solution

To get the current year in JavaScript, call the new Date() constructor to get a date object.

Let's see an example

const date = new Date();
console.log(date);

Output

2023-01-01T15:39:14.057Z

Of course, I have this date today, but it will be different for you.

Now that we have the full date, we will call a function called getFullYear to get full year.

Example

const date = new Date();

const year = date.getFullYear();

console.log(year);

Output

2023

We can also get a full year of a specific date.

// Specific date 👇️👇️
const date = new Date('January 25, 2030 05:24:07');

const yearOfDate = date.getFullYear();

console.log(yearOfDate);

Output

2030

What if we want to get the month?

There is also a built-in function to do this called getMonth, so don't worry.

// 👇️ Get Month

const date = new Date();

const month = date.getMonth() + 1;

console.log(month);

Output

1

But why +1?

That's because getMonth method returns the month in the specified date according to local time, as a zero-based value.

Well, What if we want to get the day?

// 👇️ Get Day

const date = new Date();

const day = date.getDate();

console.log(day);

Output

1

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: