php中的时间计算(加10个小时)?

问题描述 投票:20回答:7

我有时间:

$today = time();
$date = date('h:i:s A', strtotime($today));

如果当前时间是“凌晨1:00:00”,我如何再增加10个小时才能成为上午11:00:00?

php time addition
7个回答
49
投票

strtotime()给你一个代表一个秒的时间的数字。要增加它,请添加要添加的相应秒数。 10小时= 60 * 60 * 10 = 36000,所以......

$date = date('h:i:s A', strtotime($today)+36000); // $today is today date

编辑:我原以为你今天有一个字符串时间 - 如果你只是使用当前时间,甚至更简单:

$date = date('h:i:s A', time()+36000); // time() returns a time in seconds already

20
投票
$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.

DateTime Class(PHP 5> = 5.2.0)


6
投票

$date = date('h:i:s A', strtotime($today . ' + 10 hours'));

(另)


6
投票

您可以简单地使用DateTime类,OOP Style。

<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m

3
投票
$date = date('h:i:s A', strtotime($today . " +10 hours"));

2
投票

完整代码现在显示,10分钟后添加.....

$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;

0
投票

为了使用strtotime增加或减少时间,你可以在第一个参数中使用Relative format

在您的情况下,将当前时间增加10小时:

$date = date('h:i:s A', strtotime('+10 hours'));

如果您需要将更改应用于另一个时间戳,则可以指定第二个参数。

注意:

不建议使用此函数进行数学运算。最好在PHP 5.3及更高版本中使用DateTime::add()和DateTime :: sub(),或在PHP 5.2中使用DateTime :: modify()。

所以,自PHP 5.3以来的推荐方式:

$dt = new DateTime(); // assuming we need to add to the current time
$dt->add(new DateInterval('PT10H'));
$date = $dt->format('h:i:s A');

或使用别名:

$dt = date_create(); // assuming we need to add to the current time
date_add($dt, date_interval_create_from_date_string('10 hours')); 
$date = date_format($dt, 'h:i:s A');

在所有情况下,除非指定了时区,否则将使用默认时区。

© www.soinside.com 2019 - 2024. All rights reserved.