Home > Mobile >  PHP | Parse specific german date format to yyyy-mm-dd
PHP | Parse specific german date format to yyyy-mm-dd

Time:05-08

Hey I am struggling with a date format . I need to adjust the display of some dates in a wordpress project.

Its not a duplicate of This question I tried the suggestion over there and its not working with that specific date format.

What I have is german date in the format D, d. MM yyyy looking like this: Fr, 6. Mai 2022

I want to convert it to yyyy-mm-dd = 2022-05-06 but I cant get it work. I have tried to use date_parse_from_format and date_create_from_format but it seems to fail because of the german month and day names.

$date_german = 'Fr, 6. Mai 2022';
$date_english = 'Fri, 6. May 2022';
print_r(date_create_from_format('D, d. F Y', $date_german)); // doesn't work
print_r(date_create_from_format('D, d. F Y', $date_english)); // works ()

Another try with IntlDateFormatter

$date = 'Fr, 6. Mai 2022';
$formatter = new IntlDateFormatter("de_DE", IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
$formatter->setPattern('D, d. F Y');
$unixtime=$formatter->parse($date);
$datetime=new DateTime();
$datetime->setTimestamp($unixtime);
echo $datetime->format('Y-m-d');

Not working either, it returns: 1970-01-01 because $unixtime is empty?

I also tried to setLocale to de_DE before formatting, but still same problem.

CodePudding user response:

The IMO correct way to do this is indeed to use IntlDateFormatter however you're using the wrong format constants.

This should work:

$date = 'Fr, 6. Mai 2022';
$formatter = new IntlDateFormatter("de_DE", IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
$formatter->setPattern('EEEEEE, d. MMM y');
$unixtime=$formatter->parse($date);
$datetime=new DateTime();
$datetime->setTimestamp($unixtime);
echo $datetime->format('Y-m-d');

The list of constants for intl is at https://unicode-org.github.io/icu/userguide/format_parse/datetime/

  • Related