我需要使用PHP的DateTime()
. 它当前显示的是GMT时间,而不是WordPress管理中为时区设置(EST)设置的时间。
如何将其转换为显示时基
$time = new DateTime();
echo $time->format("Y-m-d h:i:s");
// 2015-08-12 04:35:34 (gmt)
// 2015-08-12 12:35:34 (what i want -- EST)
我需要使用PHP的DateTime()
. 它当前显示的是GMT时间,而不是WordPress管理中为时区设置(EST)设置的时间。
如何将其转换为显示时基
$time = new DateTime();
echo $time->format("Y-m-d h:i:s");
// 2015-08-12 04:35:34 (gmt)
// 2015-08-12 12:35:34 (what i want -- EST)
就我所知(从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() );
我在我的lib中开发了一种方法来检索当前WP的时区作为适当的对象:WpDateTimeZone::getWpTimezone()
.
虽然timezone_string
简单明了(它已经是一个有效的时区名称),gmt_offset
这个案子很棘手。我能想到的最好办法就是把它转换成+00:00
格式:
$offset = get_option( \'gmt_offset\' );
$hours = (int) $offset;
$minutes = ( $offset - floor( $offset ) ) * 60;
$offset = sprintf( \'%+03d:%02d\', $hours, $minutes )
DateTime
a应用程序aDateTimeZone
参数,您可以从WordPress选项中获取。类似于:
$time = new DateTime(NULL, get_option(\'gmt_offset\'));
编辑:我正在测试它,我得到一个错误。我不知道如何转换timezone string
到aDateTimeZone
对象,但这就是方法。
我对在WordPress中使用日期/时间和时区有点困惑。我有以下问题:“管理->设置”部分中时区设置的目的是什么?假设当前格林尼治时间是20:00,假设我在东部时间(东部时间是16:00),那么博客的时间是如何节省的?假设一位读者正在阅读帖子,而他/她位于土耳其。所以他们的当地时间是23:00,他们认为23:00是发布时间吗?假设我使用的是自定义帖子类型,并且我有一个额外的日期/时间字段用于其他日期信息。如何确保自定义日期字段的行为与WordPress字段相同?对于这些基本问题,我深表歉意,但我真的