by Sai gowtham

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 method 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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course