首页 > 解决方案 > 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 个小时。

标签: phpdatedatetimetimetimezone

解决方案


我改变时区的方法:

$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;

推荐阅读