Categories
JavaScript Answers

How to parse date time string in dd.mm.yyyy format with JavaScript?

Spread the love

Sometimes, we want to parse date time string in dd.mm.yyyy format with JavaScript.

In this article, we’ll look at how to parse date time string in dd.mm.yyyy format with JavaScript.

How to parse date time string in dd.mm.yyyy format with JavaScript?

To parse date time string in dd.mm.yyyy format with JavaScript, we can call the string split method.

For instance, we write

const strDate = "03.09.1979";
const [day, month, year] = strDate.split(".");
const date = new Date(+year, +month - 1, +day);

to call strDate.split to split the strDate string by the period.

Then we get the day, month, and year from the split string.

Next, we pass the 3 values into the Date constructor to create a date object from them.

We subtract month by 1 before we pass it into the Date constructor since it accepts a month that starts with 0 for January.

We use + to convert each value to a number before we pass them in as arguments.

Conclusion

To parse date time string in dd.mm.yyyy format with JavaScript, we can call the string split method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *