user2723025
user2723025

Reputation: 547

php get locale specific date format

What is the best way to determine the short date format for the current given locale?

For example, if my script's locale was set to Dutch, I would like to somehow obtain the short date format used in that specific locale, it would be:

dd-mm-yyyy

If it was set to American, I would like to get the date format in the American locale:

mm/dd/yyyy

And so on...

Upvotes: 9

Views: 6493

Answers (1)

Amal Murali
Amal Murali

Reputation: 76666

You can use the Intl PHP extension to format the date according to the chosen locale:

$locale = 'nl_NL';

$dateObj = new DateTime;
$formatter = new IntlDateFormatter($locale, 
                        IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);

echo $formatter->format($dateObj);

If you're just trying to get the pattern used for formatting the date, IntlDateFormatter::getPattern is what you need.

Example from the manual:

$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . $fmt->getPattern();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . $fmt->getPattern();
echo 'Second Formatted output is ' . $fmt->format(0);

This will output:

pattern of the formatter is : MM/dd/yyyy
First Formatted output is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output is 19690031 04:00:00 PST

Upvotes: 12

Related Questions