[英]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.