添加'x'到目前为止的小时数

Jon*_*atz 66 php datetime date dateadd hour

我目前有php获取当前时间/日期,如下所示:

$now = date("Y-m-d H:m:s");
Run Code Online (Sandbox Code Playgroud)

我喜欢做的是有一个$new_time等于$now + $hours+ 的新变量$hours.$new_time小时数从24到800不等.

有什么建议?

fdo*_*mig 107

您可以使用类似strtotime()函数的功能向当前时间戳添加内容.$new_time = date("Y-m-d H:i:s", strtotime('+5 hours')).

如果你需要函数中的变量,那么你必须使用双引号strtotime("+{$hours} hours"),但是你可以更好地使用它strtotime(sprintf("+%d hours", $hours)).


FAj*_*jir 37

另一个解决方案(面向对象)是使用DateTime :: add

例:

$now = new DateTime(); //current date/time
$now->add(new DateInterval("PT{$hours}H"));
$new_time = $now->format('Y-m-d H:i:s');
Run Code Online (Sandbox Code Playgroud)

PHP文档.

  • 这里的小错误,$ date-> format应该是$ now-> format (3认同)

Zar*_*Zar 19

你可以使用 strtotime()来实现这个目的:

$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours
Run Code Online (Sandbox Code Playgroud)


Rod*_*zim 10

正确

你可以使用strtotime()来实现这个目的:

$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', strtotime($now))); // $now + 3 hours
Run Code Online (Sandbox Code Playgroud)


Muh*_*ram 7

我用这个,效果很酷。

//set timezone
date_default_timezone_set('GMT');

//set an date and time to work with
$start = '2014-06-01 14:00:00';

//display the converted time
echo date('Y-m-d H:i',strtotime('+1 hour +20 minutes',strtotime($start)));
Run Code Online (Sandbox Code Playgroud)


小智 6

为“现在”添加 2 小时

$date = new DateTime('now +2 hours');
Run Code Online (Sandbox Code Playgroud)

或者

$date = date("Y-m-d H:i:s", strtotime('+2 hours', $now)); // as above in example
Run Code Online (Sandbox Code Playgroud)

或者

$now = new DateTime();

$now->add(new DateInterval('PT2H')); // as above in example
Run Code Online (Sandbox Code Playgroud)


Ank*_*kit 5

您还可以使用Unix样式时间来计算:

$newtime = time() + ($hours * 60 * 60); // hours; 60 mins; 60secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $newtime) ."\n";
Run Code Online (Sandbox Code Playgroud)


vr_*_*ver 5

嗯...您的会议记录应该更正...'i'是会议记录。不是几个月。:)(我也遇到同样的问题。

$now = date("Y-m-d H:i:s");
$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours
Run Code Online (Sandbox Code Playgroud)