Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a german date string into a date correctly?

I have a string, which I want to convert to a Date;

let dateStr = "01.04.1990"
let date = new Date(dateStr);

but if I try to console log the date I get Thu Jan 04 1990 00:00:00. As you see day and month are switched but why? How would I convert that string correctly?

like image 201
Opat Avatar asked Jan 20 '26 00:01

Opat


2 Answers

You could reorder the values for an ISO date string and get the instance with this value.

let dateStr = "01.04.1990"
let date = new Date(dateStr.replace(/(.*)\.(.*)\.(.*)/, '$3-$2-$1'));

console.log(date);
like image 135
Nina Scholz Avatar answered Jan 21 '26 13:01

Nina Scholz


In genereal Date.parse() is expecting an ISO-8601 formatted date string.

A recommendable approach would be to use a library like Luxon, as suggested here: stackoverflow

like image 25
techercu Avatar answered Jan 21 '26 14:01

techercu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!