如何在WordPress中获取当前日期和时间?

7

可能你已经知道,在 WordPress 的主题/插件作者中,强烈建议不要使用 PHP 函数如 date_default_timezone_set 更改 WordPress 的时区。

除此之外,如果没有通过 PHP 设置默认时区,当你使用 PHP 的 date 函数时,你可能会收到错误的日期和时间值。

我是说,即使在 WordPress->设置->常规->时区选项中选择了时区,date('G') 可能会显示为 10,而实际上是 15 点。

那么,如果你需要在 WordPress 网站中以所选时区获取正确的日期和时间值,应该怎么做呢?

4个回答

14

WordPress 5.3+

您可以使用current_datetime函数。它返回一个DateTimeImmutable对象,其中包含WordPress常规选项中选择的时区。然后,您可以使用对象的format或其他方法来获取所需的日期和时间。

$current_datetime = current_datetime()->format('Y-m-d H:i:s');

在 WordPress 5.3 之前

你应该使用 WordPress 的 current_time 函数来获取本地日期和时间,而不是使用 PHP date 函数。它会根据 WordPress 常规选项中选择的时区返回正确的值。

对于我来说,current_time('G') 返回 15,而 PHP 的 date('G') 返回 10,这是不正确的。

希望它能帮助一些人,因为我在 stackoverflow 上没有找到相关的主题。


current_time 已经过时,不能在当前版本的 WordPress 中使用:https://make.wordpress.org/core/2019/09/23/date-time-improvements-wp-5-3/ - Marcio Duarte

1
自WordPress 5.3版本起,您可以使用current_datetime来正确获取它:
$current_date_time = current_datetime()->format('Y-m-d H:i:s');

结果将遵循 WordPress 仪表盘中 设置 → 常规 → 时区 选择字段所定义的时区。

另请参阅 可用的格式选项

注意:请不要再使用 current_time它已不再推荐使用


0
你应该在 WordPress 中使用 current_time 函数来获取本地日期和时间,而不是使用 PHP date 函数。这样它会根据 WordPress 常规选项中选择的时区返回正确的值给你。
 $Date_Time   = current_datetime()

根据指定的类型检索当前时间。

current_time( string $type, int|bool $gmt )

根据指定的类型检索当前时间。

来源

文件:wp-includes/functions.php

function current_time( $type, $gmt = 0 ) {
// Don't use non-GMT timestamp, unless you know the difference and really need to.
if ( 'timestamp' === $type || 'U' === $type ) {
    return $gmt ? time() : time() + (int) ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
}

if ( 'mysql' === $type ) {
    $type = 'Y-m-d H:i:s';
}

current_time 不再推荐使用。但是你的代码引用了 current_datetime,这是另一个目前推荐使用的函数。https://developer.wordpress.org/reference/functions/current_datetime/ - Marcio Duarte

0

您还可以安装像当前日期短代码这样的插件,以在您所在的时区显示当前时间。它还提供了各种日期和时间格式的概述。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接