按国家

时间:2017-05-29 11:15:28

标签: php mysql laravel php-carbon

我有MySQL格式的日期,我想显示本地化为用户县日期格式的日期。

我想知道是否有办法通过国家/地区的ISO代码获取格式,例如:

$mysql_date = '2017-12-31';
echo print_localized_date($mysql_date,'it'); // 31/12/2017
echo print_localized_date($mysql_date,'de'); // 31.12.2017
echo print_localized_date($mysql_date,'us'); // 12/31/2017

我知道我可以直接传递格式,但我们的网站可能会在全世界销售,我应该考虑每种日期格式。

另一个解决方案可能是在我的国家/地区表中存储一个带有PHP日期格式字符串的列,在这种情况下是否有一个资源可以从中获取该信息,希望是CSV还是SQL转储?

我使用Laravel和Carbon,但我没有在该库中看到解决方案,例如moment.j正是我正在寻找的内容:["moment.js Multiple Locale Support][1]但是在JavaScript中,我需要它在PHP中

3 个答案:

答案 0 :(得分:5)

IntlDateFormatter扩展程序中intl的用途是什么:

$fmt = new IntlDateFormatter(
    'it_IT',
    IntlDateFormatter::SHORT,
    IntlDateFormatter::NONE,
    'Europe/Rome',
    IntlDateFormatter::GREGORIAN
);

$mysql_date = '2017-12-31';
$date = new DateTime($mysql_date);

echo $fmt->format($date);
31/12/17

答案 1 :(得分:0)

如何做到这一点的一个例子是使用PHP setlocale函数,如下所示:

setlocale(LC_TIME, "de_DE"); //sets to German locale
$today = strftime("%A, %e %B %Y"); //outputs the current time in this locale, to a string 
setlocale(LC_TIME, "en_GB"); //revert the locale back to the page standard (in my case GB).  

结合strftime函数,这将为您提供完整的语言环境感知日期和时间。

通过阅读有关此主题的类似问题,使用上述方法似乎是最简单的方法,但是comment by Terminus是一个好点 - 为什么不让前端处理这个前端问题?

完整的功能解决方案:

注意:您应该使用以下命令将来自MySQL数据列的直接9个时间戳的时间戳恢复为https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp):

SELECT ..., UNIX_TIMESTAMP(`date_column`) AS timeStampDate, ... FROM ...

这比使PHP生成DateTime对象或者需要对日期字符串进行后处理以获得相同值更有效。但是一旦达到此值,则使用以下函数:

function print_localized_date($timestamp, $locale){
    if($timestamp > 0 && !empty($locale)){
        //grab current locale
        $currentLocale = setlocale(LC_TIME, 0);
        // set to new locale.
        setlocale(LC_TIME, $locale);
        // format the date string however you wish, using the timestamp
        $today = strftime("%A, %e %B %Y", $timestamp);
        // revert to the current locale now date string is formatted.
        setlocale(LC_TIME, $currentLocale);
        // tidy up (probably un-needed)
        unset(currentLocale);
        // return the date value string.   
        return $today;
    }
    return false;
}

$timestamp = 1496061088;
$locale = "it_IT.UTF-8"; 
print print_localized_date($timestamp, $locale);
/***
 * prints lunedì, 29 maggio 2017 
 ***/

答案 2 :(得分:-1)

我会选择Carbon和" setLocale()"。

setlocale(LC_TIME, config('app.locale')); // or 'en' ..
Carbon::now()->format('l j F Y H:i:s');

或者只是在中心位置调用setLocale,例如AppServiceProvider的der regsister()方法