我几乎什么都试过了。。但wp_next_scheduled('hook_task')
总是返回1小时后的时间(我的本地时区是UTC+1,任务调度程序设置为每分钟运行一次)。
我尝试这种转换:
echo gmdate('Y-m-d H:i:s',wp_next_scheduled('hook_task'));
echo date('Y-m-d H:i:s',current_time(wp_next_scheduled('hook_task')));
echo date('Y-m-d H:i:s',current_time(wp_next_scheduled('hook_task'), 1));
但一切都会返回19:05
当下一个函数返回正确的本地时间20:05时:
echo date('Y-m-d H:i:s',current_time("timestamp"));
date_default_timezone_get()
返回UTC
如何为下一次计划跑步获取正确的当地日期时间20:05?
测试
我已经根据您的回答进行了尝试:
1) 首次测试
echo 'ACTUAL: ' . date('Y-m-d H:i:s',current_time("timestamp")) . '<br>';
$date = new DateTime("now", new DateTimeZone('Europe/Bratislava'));
echo 'WITH TZ: ' . $date->format('Y-m-d H:i:s') . '<br>';
$time = wp_next_scheduled('hook_task');
$date = new DateTime("@$time", new DateTimeZone('Europe/Bratislava'));
echo 'RESULT: ' . $date->format('Y-m-d H:i:s');
我也尝试过:$date = new DateTime("@$time", new DateTimeZone('Asia/Bangkok'));
,但无论我设置为时区,它总是返回相同的结果。
结果:
ACTUAL: 2015-12-12 22:45:10 // correct
WITH TZ: 2015-12-12 22:45:10 // correct
RESULT: 2015-12-12 21:45:39 // incorrect
2)正确的解决方案
$time = wp_next_scheduled('hook_task');
echo 'RESULT2: ' . get_date_from_gmt( date('Y-m-d H:i:s', $time) );
结果:
RESULT2: 2015-12-12 22:45:39 // correct
Wordpress每次执行任务时都会使用GMT时间戳来重新安排任务,因此为了在本地时间戳中转换时间戳,您需要添加本地时间与GMT时间的偏移量。
幸运的是,有一个叫做get_date_from_gmt
的函数
只需添加
gmt_offset
选项的值
这是代码:
$time = wp_next_scheduled('hook_task');
echo get_date_from_gmt( date('Y-m-d H:i:s', $time) );