format string 05.11.2022 into date 11/5/2022 in 3 different ways in javascript

There are several ways to format a string into a date in JavaScript. Here are three ways to format the string "05.11.2022" into the date format "11/5/2022":

1. Using string manipulation

One way to do this is to split the string into day, month, and year parts and then re-arrange them into the desired format:

index.tsx
const inputString = "05.11.2022";
const parts = inputString.split(".");
const outputString = `${parts[1]}/${parts[0]}/${parts[2]}`;
const date = new Date(outputString);
console.log(date); // Output: 2022-11-05T08:00:00.000Z
224 chars
6 lines

2. Using Moment.js library

Moment.js is a popular JavaScript library for working with dates. You can use it to easily parse and format dates:

index.tsx
const inputString = "05.11.2022";
const outputString = moment(inputString, "DD.MM.YYYY").format("M/D/YYYY");
const date = new Date(outputString);
console.log(date); // Output: 2022-11-05T08:00:00.000Z
201 chars
5 lines

3. Using date-fns library

date-fns is another JavaScript library for working with dates. Here's how you can use it to format the input string:

index.tsx
const inputString = "05.11.2022";
const outputString = format(parse(inputString, "dd.MM.yyyy", new Date()), "M/d/yyyy");
const date = new Date(outputString);
console.log(date); // Output: 2022-11-05T08:00:00.000Z
213 chars
5 lines

All three methods above will output the same result, a date object representing November 5th, 2022.

gistlibby LogSnag