Michael
Michael

Reputation: 471

PHP timezone only changing part of the times

I am trying to display an event time in three different timezones, so I set the time in a text field ("2:00 pm") with by default is EDT, and the output should be:

2:00 pm EDT / 1:00 pm CDT / 11:00 am PDT

But instead it's just showing as:

2:00 pm EDT / 2:00 pm CDT / 2:00 pm PDT

So, the times are not converting, but the timezone is. Here is my code:

// 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>';
}

You can see that I'm getting the timezone initials (EDT, CDT, PDT) from the date() function, which all change just fine, but the actual times are not. I tried switching to 'H:i' instead of 'g:i', but it just changes to 7pm, 6pm and 4pm, which are all 5 hours ahead.

Upvotes: 0

Views: 25

Answers (1)

Hirbod
Hirbod

Reputation: 67

my way to change timzones:

$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

make sure you type hint:

use DateTime, DateTimeZone;

Upvotes: 1

Related Questions