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


Add 'x' number of hours to date

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

$now = date("Y-m-d H:m:s");

我想做的是让一个新的变量$new_time等于$now + $hours,其中$hours是24到800之间的小时数。

有什么建议吗?

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

如果函数中需要变量,则必须像strtotime("+{$hours} hours")那样使用双引号,但最好使用strtotime(sprintf("+%d hours", $hours))

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

示例:

<?php
$now = new DateTime(); //now
echo $now->format('Y-m-d H:i:s'); // 2021-09-11 01:01:55
$hours = 36; // hours amount (integer) you want to add
$modified = (clone $now)->add(new DateInterval("PT{$hours}H")); // use clone to avoid modification of $now object
echo "'n". $modified->format('Y-m-d H:i:s'); // 2021-09-12 13:01:55

运行脚本


  • DateTime::添加PHP文档
  • DateInterval::构造PHP文档

您可以使用strtotime()来实现这一点:

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

正确

您可以使用strtotime()来实现这一点:

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

您还可以使用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";

我用这个,它的工作很酷。

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

嗯。。。你的会议记录应该被更正…"我有几分钟的时间。不是几个月。:)(我也有同样的问题。

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

表示将2小时添加到";现在";

$date = new DateTime('now +2 hours');

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

$now = new DateTime();
$now->add(new DateInterval('PT2H')); // as above in example

$to = date('Y-m-d H:i:s'); //"2022-01-09 12:55:46"

$from = date("Y-m-d H:i:s", strtotime("$to -3 hours")); // 2022-01-09 09:55:46

您可以尝试lib Ouzo goodies,并以流畅的方式做到这一点:

echo Clock::now()->plusHours($hours)->format("Y-m-d H:m:s");

API允许多个操作。

对于给定的DateTime,您可以添加天、小时、分钟等。以下是一些示例:

$now = new 'DateTime();
$now->add(new DateInterval('PT24H')); // adds 24 hours
$now->add(new DateInterval('P2D')); // adds 2 days

PHP:DateTime::add-手动https://www.php.net/manual/fr/datetime.add.php

$date_to_be-added="2018-04-11 10:04:46";
$added_date=date("Y-m-d H:i:s",strtotime('+24 hours', strtotime($date_to_be)));

date()和strtotime()函数的组合就可以了。

   $now = date("Y-m-d H:i:s");
   date("Y-m-d H:i:s", strtotime("+1 hours $now"));