在php中添加2小时的日期格式


Add 2 hours to date format in php

我尝试在php (wordpress)中添加+2小时的日期函数可视化。
我的代码是

function my_last_login( ) {
return 'j F Y H:i';
}

it print 21 October 2015 15:36 I want 21 October 2015 17:36
我已经尝试过strtotime,但我不擅长php。I tried

function my_last_login( ) {
return ('j F Y H:i',strtotime('+2 hours'));
}

根据php文档,你可以做类似的事情:

<?php
    $date = new DateTime('2000-01-01');
    $date->add(new DateInterval('P2H'));
    echo $date->format('Y-m-d H:i:s') "'n";
    ?>

或您可以将日期时间设置为您的时区日期,以避免添加或减去查看该页的示例,下面是该页的代码片段:

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "'n"; 

如何找到正确的时区并将其放入date_default_timezone_set()函数中?这里是时区列表。您只需要找到与您的时间相差2小时的时区。

这个问题还有另一个答案。在你的源代码中使用这个函数。

 function dateAddAnHour($date = null, $howManyHours = 1, $format = 'Y-m-d H:i:s') {
    $new_date = new 'DateTime($date);
    $new_date->modify('+'.$howManyHours.' hour');      
    return $new_date->format($format);
 }
使用

echo dateAddAnHour('2018-07-20 01:00:00', 2); // Outputs 2018-07-20 03:00:00
echo dateAddAnHour('2018-07-20 23:00:00', 2); // Outputs 2018-07-21 01:00:00

希望这对你有帮助!

如果my_last_login只有return使用日期格式string,那么您将无法在函数内添加2小时。

为了修改日期,您必须找到my_last_login被调用的位置。

日期修改示例:

$date_format_string = 'j F Y H:i';
$test_date_string = "21 October 2015 16:37";
$test_date_timestamp = strtotime($test_date_string);
$test_date = date($date_format_string, $test_date_timestamp);
$future_date_timestamp = strtotime($test_date_string . " +2 hours");
echo "Test Date (string): " . $test_date_string;
echo "<br>";
echo "Test Date Timestamp (integer): " . $test_date_timestamp;
echo "<br>";
echo "Future Date Timestamp (+2 Hours): " . $future_date_timestamp;
echo "<br>";
echo "Future Date (string): " . date($date_format_string, $future_date_timestamp);

php date接受两个参数:string $formatint $timestamp;它返回一个格式化的日期字符串。

php strtotime接受两个参数:string $timeint $timestamp;它在成功时返回一个时间戳,这对于date

来说是完美的

上面的命令将输出如下内容:

Test Date (string): 21 October 2015 16:37
Test Date Timestamp (integer): 1445445420
Future Date Timestamp (+2 Hours): 1445452620
Future Date (string): 21 October 2015 18:37