9

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...

user2723025
  • 477
  • 4
  • 16

1 Answers1

12

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
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • @user2723025: That is possible. Just use `$formatter->getPattern();`. See http://www.php.net/manual/en/intldateformatter.getpattern.php – Amal Murali Mar 29 '14 at 21:56
  • Thanks Amal, that formats the $dateObj, what I was looking for is for the actual format to be returned (I need this to extend validation of the date for a specific format as in your other post at http://stackoverflow.com/questions/19271381/correctly-determine-if-date-string-is-a-valid-date-in-that-format/19271434#19271434) In that post it checks if the date is in 'Y-m-d' format only, I need to have it adapted ideally automagically for each different locale ;-) so for nl_NL it would check 'd-m-Y' hope it's clear – user2723025 Mar 29 '14 at 21:59
  • thanks a lot, I'll extend validateDate function with the use of IntlDateFormatter – user2723025 Mar 29 '14 at 22:06