php - PHP时区仅更改部分时间
问题描述
我试图在三个不同的时区显示一个事件时间,所以我在一个文本字段(“2:00 pm”)中设置时间,默认情况下是 EDT,输出应该是:
2:00 pm EDT / 1:00 pm CDT / 11:00 am PDT
但相反,它只是显示为:
2:00 pm EDT / 2:00 pm CDT / 2:00 pm PDT
所以,时间没有转换,但时区是。这是我的代码:
// Get the value from the text field
$value = '2:00 pm';
// Let's first check to see if the value is a valid time
if( strtotime( $value ) ){
// Let's convert the time into an actual time, using today's date as filler
date_default_timezone_set( 'America/New_York' );
$time = date( 'Y-m-d g:i:s a', strtotime( 'today '.$value ) );
// List the timezones we want to return
$timezones = [
'US/Eastern',
'America/Chicago',
'America/Los_Angeles',
];
// Empty array
$display = [];
// Cycle through each timezone
foreach( $timezones as $timezone ) {
// Let's set the timezone
date_default_timezone_set( $timezone );
// Get the time in the new timezone
$new_time = date( 'g:i a T', strtotime( $time ) );
// Make the initials lowercase for the class
$ini = strtolower( date( 'T', strtotime( $value ) ) );
// Add the time to the array
$display[] = '<span class="'.$ini.'-time">'.$new_time.'</span>';
}
// Return all of the times from the array
return implode(' <span class="sep-time">/</span> ', $display );
} else {
// Else state it's not valid
return '<strong>INVALID TIME FORMAT - PLEASE USE "H:MM AM/PM"</strong>';
}
你可以看到我从date()
函数中得到了时区的首字母(EDT、CDT、PDT),这些都改变得很好,但实际时间不是。我尝试切换到'H:i'
而不是'g:i'
,但它只是更改为晚上 7 点、下午 6 点和下午 4 点,这都提前了 5 个小时。
解决方案
我改变时区的方法:
$time = new DateTime("now", new DateTimeZone("UTC");
$time->setTimezone(new DateTimeZone("US/Eastern")); // now it's US/Eastern
$time->setTimezone(new DateTimeZone("America/Chicago")); // now it's America/Chicago
确保输入提示:
use DateTime, DateTimeZone;
推荐阅读
- javascript - 如何提高基于 DFS 的迷宫游戏性能?
- c++ - C++ 信号和插槽不工作:插槽不响应事件
- python - Pyspark - 如何根据 dataframe2 中的列值在 dataframe 1 中插入记录
- c# - 使用 SDK v3 来自 Cosmos DB 的 408 状态代码
- flutter - 如何在 Flutter (dart) 中计算自然对数
- assembly - 在变址寄存器 XL(汇编语言)中直接在 STM8S103F2 控制器中加载值
- 3d - Meshlab 在使用泊松曲面重建时会产生奇怪的气泡
- python - 如何获取django项目的项目根目录
- java - QuickSort Java 代码给出错误 Time Limit Exceeded
- java - 多个随机数结果