Last active
March 31, 2017 20:31
-
-
Save JDGrimes/3b34c8ce4c79cbe3dcb2f05486458e3a to your computer and use it in GitHub Desktop.
Tests different methods of timezone handling in WordPress.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class WP_Time_Test extends WP_UnitTestCase { | |
public function test_strtotime() { | |
$offset = -5; | |
update_option( 'gmt_offset', $offset ); | |
update_option( 'timezone_string', 'America/New_York' ); | |
// A date relative to the site's timestamp. | |
$current_date = current_time( 'mysql' ); | |
// Convert it to a timestamp. | |
$current_time = strtotime( $current_date ); | |
// Remember, strtotime() uses the default timezone if none is supplied. | |
// This means that it just handed us a timestamp for when that datetime | |
// occurred in the GMT timezone. We have to correct that to the time | |
// that that datetime occurred in our current timezone, by removing the | |
// excess based on the our current UTC offset. | |
// This will be wrong if DST! | |
$current_time -= $offset * HOUR_IN_SECONDS; | |
// Then convert the timestamp back to date format. | |
$gmt_date_from_current = gmdate( 'Y-m-d H:i:s', $current_time ); | |
// Now, get the straight GMT date. | |
$current_date_gmt = current_time( 'mysql', true ); | |
// The one that we converted from the site's timezone should match exactly. | |
$this->assertSame( $current_date_gmt, $gmt_date_from_current ); | |
} | |
public function test_datetime_object() { | |
update_option( 'gmt_offset', -5 ); | |
update_option( 'timezone_string', 'America/New_York' ); | |
// A date relative to the site's timezone. | |
$current_date = current_time( 'mysql' ); | |
// Create a datetime object from it, passing in the site's timezone. | |
$date = new DateTime( | |
$current_date | |
, new DateTimeZone( get_option( 'timezone_string' ) ) | |
); | |
// Option 1: | |
// Convert it to a timestamp. | |
$current_time = $date->getTimestamp(); | |
// Then convert the timestamp back to date format. | |
$gmt_date_from_current = gmdate( 'Y-m-d H:i:s', $current_time ); | |
// Now, get the straight GMT date. | |
$current_date_gmt = current_time( 'mysql', true ); | |
// The one that we converted from the site's timezone should match exactly. | |
$this->assertSame( $current_date_gmt, $gmt_date_from_current ); | |
// Option 2: | |
// If we change the timezone to UTC... | |
$date->setTimezone( new DateTimeZone( 'UTC' ) ); | |
// ...we can also convert it using the format() method. | |
$this->assertSame( $current_date_gmt, $date->format( 'Y-m-d H:i:s' ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment