[英]Get PHP date_format string by country
我有一个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中。
这就是来自intl扩展名的IntlDateFormatter
的用途:
$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
如何做到这一点的示例是使用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
函数结合使用,将为您提供PHP中完全符合区域设置的日期和时间。
通过阅读有关该主题的类似问题,使用上述方法似乎是最简单的方法,但是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
***/
我将使用Carbon和“ setLocale()”。
setlocale(LC_TIME, config('app.locale')); // or 'en' ..
Carbon::now()->format('l j F Y H:i:s');
或者只是在中央位置调用setLocale,例如在AppServiceProvider的der regsister()方法中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.