5

I'm trying to rely on IntlDateFormatter to return the current date in a locale-based format. This means DD/MM/YYYY for it_IT, de_DE, fr_FR... or MM/DD/YYYY for en_US and so on for all the possible locales.

I'm trying to follow the same solution I used to retrieve the current month's name:

$formatter = new IntlDateFormatter("it_IT", IntlDateFormatter::FULL, IntlDateFormatter::FULL);
$formatter->setPattern("MMMM");
return $formatter->format($this);

This code correctly returns "January", "gennaio" etc.

The problem is, I cannot figure out the right pattern to get the date in the current locale format. The ICU User Guide mentions the DateTimePatternGenerator class, and this looks like it! But I cannot find it in PHP.

I would like to avoid a custom, huge switch-case and rely on built-in function instead.

It must be pure PHP.

Any help?

4

1 Answer 1

1

I'm not sure if you want to get pattern from ICU itself, or just format your DateTime. Here you have both solutions.

Basics:

You're doing well with you actual code for retrieving month name. IntlDateFormatter is pretty customizable, and it all depend on options you gave it.

Getting date with year, month and day depending on locale:

$locale = "en_GB";
$dateType = IntlDateFormatter::SHORT;//type of date formatting
$timeType = IntlDateFormatter::NONE;//type of time formatting setting to none, will give you date itself
$formatter =new IntlDateFormatter($locale, $dateType, $timeType);
$dateTime = new DateTime("2015-02-28");
echo $formatter->format($dateTime);

will give you

28/02/2015

You can play with other options of IntlDateFormatter. There's SHORT, MEDIUM, LONG, FULL and NONE - you can read about them and check example ouput here.

Getting pattern from formatter

$formatter->->getPattern();

will give you something like

dd/MM/yyyy

I hope this will help you. I've been struggling with it for a long time to do it properly :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.