How to merge get current month - JavaScript

Mo Ibra

Mo Ibra

Jan 1, 2023

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

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


Problem

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


Solution

To get the current month 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 getMonth to get full month.

Example

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.

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

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

const monthOfDate = date.getMonth() + 1;

console.log(monthOfDate);

Output

2

What if we want to get the year?

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

// 👇️ Get year

const date = new Date();

const year = date.getFullYear();

console.log(year);

Output

2023

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: