Skip to content

Instantly share code, notes, and snippets.

@codearachnid
Last active September 19, 2023 17:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codearachnid/4704496 to your computer and use it in GitHub Desktop.
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.
<?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