How to use Date() constructor In Javascript

Creating date object using date string: The date() constructor creates a date in human-understandable date form.

Example: In this example, we will convert a string into a date by creating a date object.

javascript
// It returns the Day,Month,Date,Year and time
// Using Date() constructor
let d = new Date("May 1,2019 11:20:00");

// Display output
console.log(d);

Output
2019-05-01T11:20:00.000Z

Getting the string in DD-MM-YY format using suitable methods: We use certain methods such as:

  • getDate-It Returns Day of the month(from 1-31)
  • getMonth-It returns month number(from 0-11)
  • getFullYear-It returns full year(in four digits )

Example: This example uses the approach to convert a string into a date.

Javascript
// Using Date() constructor
let d = new Date("May 1, 2019 ");

// Display output
console.log(formatDate(d));
    
// Funciton to extract day, month, and year 
function formatDate(date) {
    let day = date.getDate();
    if (day < 10) {
        day = "0" + day;
    }
    let month = date.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    }
    let year = date.getFullYear();
    return day + "/" + month + "/" + year;
}

Output
01/05/2019

Convert string into date using JavaScript

In this article, we will convert a string into a date using JavaScript. A string must follow the pattern so that it can be converted into a date.

A string can be converted into a date in JavaScript through the following ways:

Table of Content

  • Using JavaScript Date() constructor
  • Using JavaScript toDateString() method
  • Using Date.parse() method
  • Using Intl.DateTimeFormat() and new Date():

Similar Reads

Method 1: Using JavaScript Date() constructor

Creating date object using date string: The date() constructor creates a date in human-understandable date form....

Method 2: Using JavaScript toDateString() method

This method returns the date portion of the Date object in human-readable form....

Method 3: Using Date.parse() method

The JavaScript Date parse() Method is used to know the exact number of milliseconds that have passed since midnight, January 1, 1970, till the date we provide....

Method 4: Using Intl.DateTimeFormat() and new Date():

Using Intl.DateTimeFormat() and new Date(), the approach formats the input string using specified options for year, month, and day. It then creates a new Date object from the formatted string, effectively converting the string into a date....

Supported Browsers

Google ChromeFirefoxEdgeOperaApple Safari...