Last active
September 19, 2023 17:21
-
-
Save codearachnid/4704496 to your computer and use it in GitHub Desktop.
Recently was working on importing dates into WordPress and needed to convert the date to the current site timezone. Because WordPress may not give you the timezone string if an UTC offset is set I modify the datetime vs change the timezone.
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 | |
/** | |
* wp_convert_to_timezone useful for adjusting an imported DateTime to your site GMT/UTC offset | |
* | |
* @link http://www.php.net/manual/en/timezones.php Accepted $timezone strings | |
* @link http://www.cs.tut.fi/~jkorpela/iso8601.html Reason for default return as ISO 8601 | |
* | |
* @param string $datetime | |
* @param string $timezone default GMT | |
* @param string $return_format default ISO 8601 | |
* @return string $datetime as $return_format | |
*/ | |
function wp_convert_to_timezone( &$datetime, $timezone = 'GMT', $return_format = 'c' ){ | |
// get site timezone offset | |
$gmt_offset = get_option( 'gmt_offset' ); | |
// setup date object with timezone | |
$datetime_obj = new DateTime( $datetime, new DateTimeZone( $timezone ) ); | |
// reset date timezone to be neutral for offset | |
$datetime_obj->setTimezone(new DateTimeZone('GMT')); | |
// modify the timezone with offset | |
$datetime_obj->modify( $gmt_offset . ' hours' ); | |
// return datetime | |
$datetime = $datetime_obj->format( $return_format ); | |
} | |
// example to convert start_time of Facebook event | |
offset_date_to_timezone( $facebook_event->start_time, 'America/Los_Angeles' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment