how do you convert a string to a date in javascript

You can use the Date() constructor to create a date object from a string. The string must be in a format recognized by the Date.parse() method or in the ISO format: YYYY-MM-DDTHH:mm:ss.sssZ. Here's an example:

index.tsx
const dateString = '2021-09-28T12:00:00.000Z';
const date = new Date(dateString);
console.log(date);
101 chars
4 lines

This will output: 2021-09-28T12:00:00.000Z.

If the string is not in the correct format or cannot be parsed, the date object will be invalid, and you can test for this using the isNaN() function.

index.tsx
const dateString = 'invalid date string';
const date = new Date(dateString);
if (isNaN(date.getTime())) {
  console.log('Invalid date');
}
139 chars
6 lines

related categories

gistlibby LogSnag