How to convert String to Date in JavaScript
In this tutorial, we are going to learn about converting a string to a date object in JavaScript.
Consider, we have a date string like this.
const str = "2020-06-11";
Now, we need to convert the above date string to an actual date object with JavaScript.
Note: The date string should be in ISO format (YYYY-MM-DD or MM/DD/YYYY or YYYY-MM-DDTHH:MM:SSZ)
Using new Date() constructor
The new Date()
constructor takes the date string
as an argument and creates the new date object.
Example:
const str = "2020-06-11";
const date = new Date(str);
console.log(date.toString());
// "Thu Jun 11 2020 05:30:00 GMT+0530 (India Standard Time)"
The toString()
method returns the string representation of the specified date.
We can also access individual information of the date by using the following methods.
getDate(): It returns the day of the month.
getMonth(): It returns the month of a year, where 0 is January and 11 is December.
getFullYear(): It returns the year in four-digit format (YYYY).
const str = "2020-06-11";
const date = new Date(str);
console.log(date.getDate()); // 11
console.log(date.getMonth()); // 5
// January is 0, so June is 5
console.log(date.getFullYear()); // 2020