1

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?

Opat
  • 93
  • 1
  • 2
  • 9
  • Use a library that supports format strings, split the string into its date parts and built the `Date` object with those parts, ... -> What have you tried so far to solve this on your own? You haven't found anything here on SO on how to parse strings? – Andreas Oct 06 '20 at 06:33
  • I will try. Maybe its time to use momentjs – Opat Oct 06 '20 at 06:34
  • @Andreas I have seen interesting posts but to be sure that I do everything up to date, I asked this question here because I do not know whether things changed or things become obsolete – Opat Oct 06 '20 at 06:39
  • 1
    Try `new Date('01.04.1990'.split('.').reverse())` – User863 Oct 06 '20 at 06:48
  • @User863 Hey, that is also a nice short solution. Thank you! – Opat Oct 06 '20 at 06:57

2 Answers2

5

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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

techercu
  • 11
  • 3
  • @Opat Except don't use moment.js. It is "done", officially. Read their homepage for why and for recommendations what to use instead. – RoToRa Oct 06 '20 at 13:18
  • @Opat RoToRa - You indeed are right - I changed the answer to Luxon since it seems to also do the job of parsing custom formats. – techercu Oct 06 '20 at 14:15