我想轉換用戶的時間,例如。08:45 P.M, 到 UTC 時區。我怎樣才能做到這一點?
if ($request->open_at)
{
$time = Carbon::parse($request->open_at)->toUTCString();
dd($time);
$query->whereTime('open_at', '>=', $time);
}
uj5u.com熱心網友回復:
像這樣,但除非您總是從系統時區(在 PHP 中配置)開始,否則 date 必須已經設定了正確的時區才能使其作業,就像其他人提到的那樣。
$time = Carbon::parse($request->open_at);
$time->setTimezone('UTC');
...
Carbon 擴展了 DateTime 物件,包括setTimezone
uj5u.com熱心網友回復:
使用這種 PHP 方法:
$time = new DateTime("08:45 P.M");
$time ->setTimezone(new DateTimeZone("UTC"));
echo $time ->format("Y-m-d H:i:s e");
uj5u.com熱心網友回復:
用戶的時區可以輸入到 的可選第二個引數中parse()。我也一直找不到任何toUTCString()方法(??)。全部一起:
$userTimeZone = 'Europe/Berlin'; // We'll come to this later
$time = Carbon::parse($request->open_at, $userTimeZone)->setTimezone('UTC');
echo $time->format('r');
例如:
foreach (['Asia/Tokyo', 'Europe/Berlin', 'America/Los_Angeles'] as $userTimeZone) {
echo "$userTimeZone\n";
$time = Carbon::parse('08:45 P.M', $userTimeZone);
echo $time->format('r'), "\n";
$time->setTimezone('UTC');
echo $time->format('r'), "\n\n";
}
Asia/Tokyo
Fri, 24 Dec 2021 20:45:00 0900
Fri, 24 Dec 2021 11:45:00 0000
Europe/Berlin
Fri, 24 Dec 2021 20:45:00 0100
Fri, 24 Dec 2021 19:45:00 0000
America/Los_Angeles
Thu, 23 Dec 2021 20:45:00 -0800
Fri, 24 Dec 2021 04:45:00 0000
當然,如果您不知道用戶的時區,所有這些都是毫無意義的。你有這樣的資訊嗎?最簡單的方法可能就是問,雖然你也可以使用一些技巧來嘗試和猜測,例如:
- 客戶端 JavaScript
- 地理定位 API
uj5u.com熱心網友回復:
Carbon 有->utc()方法(相當于setTimezone('UTC'))并且 Laravel 查詢構建可以使用 Carbon 物件而無需將其格式化為字串:
$query->whereTime('open_at', '>=', Carbon::parse($request->open_at)->utc());
uj5u.com熱心網友回復:
使用set timezone函式轉換時間
$time = Carbon::parse($request->open_at);
$time->setTimezone('UTC');
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/391969.html
