函数文档

rest_get_date_with_gmt()

💡 云策文档标注

概述

rest_get_date_with_gmt() 函数用于解析日期字符串,返回本地时间和 UTC 时间的 MySQL 格式字符串。它基于 RFC3339 时间戳,并支持指定输入是否为 UTC 时间。

关键要点

  • 函数接受两个参数:$datestring(必需,RFC3339 时间戳)和 $is_utc(可选布尔值,默认为 false)。
  • 返回一个数组,包含本地和 UTC 的 MySQL 格式日期时间字符串(Y-m-d H:i:s),失败时返回 null。
  • 内部使用 rest_parse_date() 解析时间戳,并根据时区信息进行转换。
  • 常用于 WordPress REST API 中,如 WP_REST_Posts_Controller 和 WP_REST_Comments_Controller。

代码示例

function rest_get_date_with_gmt( $date, $is_utc = false ) {
    $has_timezone = preg_match( '#(Z|[+-]d{2}(:d{2})?)$#', $date );
    $date = rest_parse_date( $date );
    if ( false === $date ) {
        return null;
    }
    if ( ! $is_utc && ! $has_timezone ) {
        $local = gmdate( 'Y-m-d H:i:s', $date );
        $utc   = get_gmt_from_date( $local );
    } else {
        $utc   = gmdate( 'Y-m-d H:i:s', $date );
        $local = get_date_from_gmt( $utc );
    }
    return array( $local, $utc );
}

注意事项

  • 函数依赖于 rest_parse_date() 进行初始解析,需确保输入为有效的 RFC3339 格式。
  • 时区处理逻辑基于输入是否包含时区信息和 $is_utc 参数,开发者需注意参数设置以避免错误转换。
  • 自 WordPress 4.4.0 版本引入,兼容性需考虑。

📄 原文内容

Parses a date into both its local and UTC equivalent, in MySQL datetime format.

Description

See also

Parameters

$datestringrequired
RFC3339 timestamp.
$is_utcbooloptional
Whether the provided date should be interpreted as UTC.

Default:false

Return

array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s), null on failure.

  • 0 string
    Local datetime string.
  • 1 string
    UTC datetime string.

Source

function rest_get_date_with_gmt( $date, $is_utc = false ) {
	/*
	 * Whether or not the original date actually has a timezone string
	 * changes the way we need to do timezone conversion.
	 * Store this info before parsing the date, and use it later.
	 */
	$has_timezone = preg_match( '#(Z|[+-]d{2}(:d{2})?)$#', $date );

	$date = rest_parse_date( $date );

	if ( false === $date ) {
		return null;
	}

	/*
	 * At this point $date could either be a local date (if we were passed
	 * a *local* date without a timezone offset) or a UTC date (otherwise).
	 * Timezone conversion needs to be handled differently between these two cases.
	 */
	if ( ! $is_utc && ! $has_timezone ) {
		$local = gmdate( 'Y-m-d H:i:s', $date );
		$utc   = get_gmt_from_date( $local );
	} else {
		$utc   = gmdate( 'Y-m-d H:i:s', $date );
		$local = get_date_from_gmt( $utc );
	}

	return array( $local, $utc );
}

Changelog

Version Description
4.4.0 Introduced.