convert a string to a date in javascript

In JavaScript, we can convert a string to a date using the Date() constructor and the parse() method.

Here is an example:

index.tsx
let dateString = '2021-11-30';
let dateObject = new Date(dateString);

console.log(dateObject);
// Output: Tue Nov 30 2021 00:00:00 GMT+0000 (Coordinated Universal Time)
170 chars
6 lines

In this example, we pass the date string to the Date() constructor to create a Date object. The resulting date object will be based on the local time zone of the browser.

Alternatively, we can use the parse() method to convert a string to a date object:

index.tsx
let dateString = '2021-11-30';
let dateObject = Date.parse(dateString);

console.log(new Date(dateObject));
// Output: Tue Nov 30 2021 00:00:00 GMT+0000 (Coordinated Universal Time)
182 chars
6 lines

In this example, we use the parse() method to first parse the date string into an number of milliseconds since January 1, 1970, 00:00:00 UTC. We then pass this number to the Date() constructor to create a Date object.

Note that the parse() method parses dates based on the ISO-8601 date format, which is YYYY-MM-DDTHH:mm:ss.sssZ. Other date formats may require additional parsing or formatting.

gistlibby LogSnag