-1

I am using JavaScript to render a date in the client culture.

(new Date("2020-01-01")).toLocaleDateString()

which, in my case, returns

"1.1.2020"

(but also could return 1/1/2020 or whatever culture the client has)

The numbers have to have at least two digits (=> 01.01.2020).

With the following I tried to identify the numbers with only one digit, but it didn't work properly in my test cases:

[^\d]([\d])[^\d]

Test cases:

1.2.2020
22.1.2000
1-2-2020
1311/29/9
2000/1/1
22/1/2000

Does anyone know how to fix this problem without splitting it into their three parts and checking each part in JavaScript?

Thanks in advance!

  • Beside non-numbers (`[^\d]`) you'll also have to check for start and end of string (`^` and `$`), something like `(^|[^\d])([\d])([^\d]|$)` or simpler `(^|\D)([\d])(\D|$)` – Titus Dec 29 '19 at 20:16
  • 2020-01-01 will be parsed as UTC, so for users west of Greenwich *toLocaleDateString* will produce a date for 2019-12-31. *toLocaleDateString* will produce different format strings depending on the host "locale" settings, or not. – RobG Dec 29 '19 at 20:24

1 Answers1

4
(new Date("2020-01-01")).toLocaleDateString("de-DE",{
  day:"2-digit",
  month:"2-digit",
  year:"numeric"
})

You can view more options here.

J3SKO
  • 101
  • 4