How to Convert String to Date in JavaScript

To convert a String to a Date in JavaScript, you can use the “Date” constructor and parse a variety of date formats, including ISO 8601 date strings and strings in the format “Month day, year”.


const dateString = '2023-04-22';

// Convert the string to a Date object
const dateObject = new Date(dateString);

// Log the Date object to the console



In this code, we have a date string called dateString.

We created a Date object called dateObject by passing the date string to the Date constructor. The Date object will represent the date specified in the string.

Remember that the Date constructor may not be able to parse all date string formats, and the parsing behavior can be browser-dependent.

For more reliable date string parsing, consider using a library like date-fns or Moment.js (note that Moment.js is no longer actively maintained and not recommended for new projects).

Leave a Comment