就我所知(从documentation), 的第二个参数DateTime::__construct()
, 如果提供,应为DateTimeZone
例子
接下来的问题是,我们如何创建DateTimeZone
例子如果用户选择了一个城市作为他们的时区,这很容易,但如果他们使用(不推荐使用的)Etc/GMT时区设置了偏移量,我们可以解决这个问题。
/**
* Returns the blog timezone
*
* Gets timezone settings from the db. If a timezone identifier is used just turns
* it into a DateTimeZone. If an offset is used, it tries to find a suitable timezone.
* If all else fails it uses UTC.
*
* @return DateTimeZone The blog timezone
*/
function wpse198435_get_blog_timezone() {
$tzstring = get_option( \'timezone_string\' );
$offset = get_option( \'gmt_offset\' );
//Manual offset...
//@see http://us.php.net/manual/en/timezones.others.php
//@see https://bugs.php.net/bug.php?id=45543
//@see https://bugs.php.net/bug.php?id=45528
//IANA timezone database that provides PHP\'s timezone support uses POSIX (i.e. reversed) style signs
if( empty( $tzstring ) && 0 != $offset && floor( $offset ) == $offset ){
$offset_st = $offset > 0 ? "-$offset" : \'+\'.absint( $offset );
$tzstring = \'Etc/GMT\'.$offset_st;
}
//Issue with the timezone selected, set to \'UTC\'
if( empty( $tzstring ) ){
$tzstring = \'UTC\';
}
$timezone = new DateTimeZone( $tzstring );
return $timezone;
}
然后您可以按如下方式使用它:
$time = new DateTime( null, wpse198435_get_blog_timezone() );