How To Create A Date From Day, Month, Year Using JavaScript

Create a Date from day, month, year using JavaScript

Javascript offers you many functions and many methods to create a date from day, month, year using JavaScript. We already tested effectively with three methods using the Date() constructor, using the replace() method, and the substring() method. Hopefully, through this article, you can easily find an easy way to do that.

Create A Date From Day, Month, Year Using JavaScript

Using the Date() constructor

JavaScript Dates offer you the constructor property that returns the function that created the Date object. This constructor can create a Date instance or return a string representing the current time. To create a date from the day, month, and year you just only using the Date (year, month, day).

Code example:

In this example, we assign the values for the year, month, and day variables.

Then, easily create a date by using the Date() constructor, but we have some notes for you.

  • The month in Javascript starts in 0, so 0 represents January, 1 represents February, etc.
  • You can also input the negative number of the month, and it will count down the months for you. Like -1 represents December, -2 represents November, -3 represents October, etc.
  • In addition, using the current month and subtracting 1 is also a good way to calculate the month in Javascript Date.

Let’s see the code example below.

const [year, month, day] = ["2022", "12", "13"];

// Using the Date constructor to create a date
var date = new Date(year, month - 1, day);
console.log(date);

Output

Tue Dec 13 2022 00:00:00 GMT+0700

Example 2:

Or you can create a date directly without creating a year, month, and day variable, and don’t forget to subtract 1 to get the month you want. Like this code example below.

// Using the Date constructor to create a date, using the month subtract 1
var date = new Date(2022, 12 - 1, 13);
console.log(date);

Output

Tue Dec 13 2022 00:00:00 GMT+0700

Example 3:

This example will use negative number input for the month.

// Using the Date constructor to create a date , use negative number input for month
var date = new Date(2022, -1, 13);
console.log(date);

Output

Tue Dec 13 2022 00:00:00 GMT+0700

Browser Support

Constructor is an ECMAScript1 (ES1) feature.

This feature is a common function in JavaScript and supported in all browsers. You can use it for all browsers.

Summary

Hopefully, through this article, you can easily create a date from day, month, year using JavaScript. We used a Date constructor to do it, but how about you? Leave your comment here if you have any questions about this article. Thank you for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *