Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date format according to the locale in PHP

There is a very simple problem. I have a locale identifier, en, en_US, cs_CZ or whatever. I just need to get the date-time format for that locale. I know I can easily format any timestamp or date object according to the locale. But I need just the string representation of the date format, let's say a regular expression. Is there any function managing this functionality? I haven't found any so far...

Exapmle:

$locale = "en_US";
$format = the_function_i_need($locale);
echo $format; // prints something like "month/day/year, hour:minute"
like image 625
Pavel S. Avatar asked Jan 11 '12 22:01

Pavel S.


People also ask

How convert date from yyyy-mm-dd to dd mm yyyy format in PHP?

Change YYYY-MM-DD to DD-MM-YYYY In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format. $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate)); echo "New date format is: ".

What can I use instead of Strftime?

Replacements. For locale-aware date/time formatting, use IntlDateFormatter::format (requires Intl extension). In a real-life and ideal use case, the IntlDateFormatter object is instantiated once based on the user's locale information, and the object instance can is used whenever necessary.

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


2 Answers

function getDateFormat($locale)
{
    $formatter = new IntlDateFormatter($locale, IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
    if ($formatter === null)
        throw new InvalidConfigException(intl_get_error_message());

    return $formatter->getPattern();
}

Make shure you install intl.

like image 200
verybadbug Avatar answered Sep 24 '22 00:09

verybadbug


I'm trying to do the same thing myself. Instead of building an array of all the countries, how about using regex to determine the format?

setlocale(LC_TIME, "us_US");

// returns 'mdy'
$type1 = getDateFormat();

setlocale(LC_TIME, "fi_FI");

// returns 'dmy'
$type2 = getDateFormat();

setlocale(LC_TIME, "hu_HU");

// returns 'ymd'
$type3 = getDateFormat();

/**
 * @return string
 */
function getDateFormat()
{
    $patterns = array(
        '/11\D21\D(1999|99)/',
        '/21\D11\D(1999|99)/',
        '/(1999|99)\D11\D21/',
    );
    $replacements = array('mdy', 'dmy', 'ymd');

    $date = new \DateTime();
    $date->setDate(1999, 11, 21);

    return preg_replace($patterns, $replacements, strftime('%x', $date->getTimestamp()));
}
like image 36
CrEOF Avatar answered Sep 24 '22 00:09

CrEOF