Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get locale specific date format

Tags:

date

php

datetime

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

like image 582
user2723025 Avatar asked Mar 29 '14 21:03

user2723025


Video Answer


1 Answers

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
like image 145
Amal Murali Avatar answered Oct 11 '22 11:10

Amal Murali