create new date form string 13.11.2022 in a safe way, give 3 ecamples in javascript

To create a new date from a string '13.11.2022', we can use the Date constructor with arguments for the year, month, and date.

Example 1: Using plain JavaScript

index.tsx
const dateString = '13.11.2022';
const parts = dateString.split('.');
const date = new Date(parts[2], parts[1] - 1, parts[0]);
console.log(date);
146 chars
5 lines

In this example, we split the string on the '.' separator, then create a new Date object with the year, month, and date. Note that we subtract 1 from the month value as JavaScript months are zero-indexed (i.e. January is 0, February is 1, etc.)

Example 2: Using moment.js library

index.tsx
const dateString = '13.11.2022';
const date = moment(dateString, 'DD.MM.YYYY').toDate();
console.log(date);
108 chars
4 lines

In this example, we use the moment.js library to parse the date string and convert it to a Date object. The 'DD.MM.YYYY' argument specifies the format of the input string.

Example 3: Using Date.parse method

index.tsx
const dateString = '13.11.2022';
const date = new Date(Date.parse(dateString.replace(/\./g, "-")));
console.log(date);
119 chars
4 lines

In this example, we use the Date.parse method to create a new date object from the string. We first replace all '.' characters with '-' to ensure that it is in a format that can be parsed by the method. Then we pass this modified string to the Date constructor.

gistlibby LogSnag