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

时间:2015-10-21 16:29:25

标签: php date

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

function my_last_login( ) {
return 'j F Y H:i';
}
它打印2015年10月21日15:36我想要2015年10月21日17:36
我已经尝试了strtotime但我不擅长PHP。 我试过了

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

4 个答案:

答案 0 :(得分:3)

如何找到合适的时区并将其放入date_default_timezone_set()功能?这是timezones的列表。您只需要找到距离您的时间+2小时的时区。

答案 1 :(得分:3)

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

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

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

// 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"; 

答案 2 :(得分:1)

好的,这是该答案的另一个替代答案。只需在源代码中使用此功能即可。

 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

希望这会有所帮助!

答案 3 :(得分:0)

如果my_last_loginreturn日期格式为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