将UTC转换为WordPress选项中时区、语言和格式的字符串我创建了一个well document函数,它可以将UTC中的日期时间字符串转换为正确语言、格式和时区的漂亮日期时间字符串。请随意复制。
For example, passing in "2019-05-30 18:06:01"
(in UTC) would return "Maggio 30, 2019 10:06 am"
.
/**
* Given a string with the date and time in UTC, returns a pretty string in the
* configured language, format and timezone in WordPress\' options.
*
* @param string $utc_date_and_time
* e.g: "2019-05-30 18:06:01"
* This argument must be in UTC.
* @return string
* e.g: "Maggio 30, 2019 10:06 am"
* This returns a pretty datetime string in the correct language and
* following the admin\'s settings.
*/
function pretty_utc_date( string $utc_date ): string {
if (! preg_match( \'/^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d$/\', $utc_date ) ) {
/* I have not tested other formats, so only this one allowed. */
throw new InvalidArgumentException( "Expected argument to be in YYYY-MM-DD hh:mm:ss format" );
}
$date_in_local_timezone = get_date_from_gmt( $utc_date );
/* $date_in_local_timezone is now something like "2019-05-30 10:06:01"
* in the timezone of get_option( \'timezone_string\' ), configured in
* WordPress\' general settings in the backend user interface.
*/
/* Unfortunately, we can\'t just pass this to WordPress\' date_i18n, as that
* expects the second argument to be the number of seconds since 1/Jan/1970
* 00:00:00 in the timezone of get_option( \'timezone_string\' ), which is not the
* same as a UNIX epoch timestamp, which is the number of seconds since
* 1/Jan/1970 00:00:00 GMT. */
$seconds_since_local_1_jan_1970 =
(new DateTime( $date_in_local_timezone, new DateTimeZone( \'UTC\' ) ))
->getTimestamp();
// e.g: 1559210761
/* Administrators can set a preferred date format and a preferred time
* format in WordPress\' general settings in the backend user interface, we
* need to retrieve that. */
$settings_format = get_option( \'date_format\' ) . \' \'. get_option( \'time_format\' );
// $settings_format is in this example "F j, Y g:i a"
/* In this example, the installation of WordPress has been set to Italian,
* and the final result is "Maggio 30, 2019 10:06 am" */
return date_i18n( $settings_format, $seconds_since_local_1_jan_1970 );
}
参考文献:
get_date_from_gmt
docsDateTimeZone
docs 在php中。净值DateTime
docs 在php中。净额,包括getTimestamp
WordPress\'date_i18n
docs值得记住的是,WordPress运行date_default_timezone_set( \'UTC\' );
无论管理员在用户界面中选择什么时区,因此在确定内置PHP函数的行为时都要记住这一点。看见date_default_timezone_set
docs 在php中。净额