get_date_from_gmt()
云策文档标注
概述
get_date_from_gmt() 是一个 WordPress 函数,用于将 UTC 或 GMT 时区的日期转换为站点时区的日期。它接受日期字符串和可选格式参数,返回格式化后的本地时间。
关键要点
- 函数接受两个参数:$date_string(必需,UTC/GMT 时区的日期字符串)和 $format(可选,返回日期格式,默认为 'Y-m-d H:i:s')。
- 返回值为字符串,表示转换后站点时区的格式化日期。
- 内部使用 date_create() 和 wp_timezone() 进行时区转换,如果输入无效则返回默认值。
- 不接受 Unix 时间戳,需先转换为日期字符串格式。
- 相关函数包括 wp_timezone()、get_gmt_from_date()(逆函数)等。
代码示例
function get_date_from_gmt( $date_string, $format = 'Y-m-d H:i:s' ) {
$datetime = date_create( $date_string, new DateTimeZone( 'UTC' ) );
if ( false === $datetime ) {
return gmdate( $format, 0 );
}
return $datetime->setTimezone( wp_timezone() )->format( $format );
}注意事项
- 输入日期必须为 Y-m-d H:i:s 格式的字符串,不支持 Unix 时间戳。
- 如果 $date_string 无效,函数返回 gmdate($format, 0) 作为默认值。
- 使用时需确保站点时区设置正确,依赖 wp_timezone() 函数。
原文内容
Given a date in UTC or GMT timezone, returns that date in the timezone of the site.
Description
Requires a date in the Y-m-d H:i:s format.
Default return format of ‘Y-m-d H:i:s’ can be overridden using the $format parameter.
Parameters
$date_stringstringrequired-
The date to be converted, in UTC or GMT timezone.
$formatstringrequired-
The format string for the returned date. Default ‘Y-m-d H:i:s’.
Source
function get_date_from_gmt( $date_string, $format = 'Y-m-d H:i:s' ) {
$datetime = date_create( $date_string, new DateTimeZone( 'UTC' ) );
if ( false === $datetime ) {
return gmdate( $format, 0 );
}
return $datetime->setTimezone( wp_timezone() )->format( $format );
}
Changelog
| Version | Description |
|---|---|
| 1.2.0 | Introduced. |
Skip to note 3 content
d4mation
get_date_from_gmt() does not accept a Unix Timestamp because date_create() doesn’t.
If you need to provide a Unix Timestamp, you will need to convert it to a different format first like the following example:
Skip to note 4 content
Geoffrey Brossard
The inverse function is get_gmt_from_date.