将当前时间添加到DateTime

时间:2013-11-24 12:10:34

标签: php datetime

我想将5天和当前时间添加到日期中,我在字符串中。

$date = new DateTime('2013-11-21');
date_add($date, date_interval_create_from_date_string('5 days'));
$curtime = date('H:i:s');

如何将当前时间添加到DateTime,或者还有其他更好的方法吗?

5 个答案:

答案 0 :(得分:3)

只需编辑您的最后一条通道 - 我认为这是解决您问题的最客观方案。其余代码是正确的。

$curtime = $date->format('Y-m-d H:i:s');

请记住,您的第二条道路只是一个别名:

$date->add(DateInterval::createFromDateString('5 days'));

所以完整的代码是:

$date = new DateTime('2013-11-21');
$date->add(DateInterval::createFromDateString('5 days'));
$curtime = $date->format('Y-m-d H:i:s');

编辑:我刚刚再次阅读了您的问题,并询问是否要将当前时间添加到此日期。如果要添加时间,则需要从当前日期创建它。这不是完美的解决方案,但我仍在努力:

$now = new DateTime(date('1970-01-01 H:i:s'));
$date->add(DateInterval::createFromDateString($now->getTimestamp() . ' seconds'));
$curtime = $date->format('Y-m-d H:i:s');
echo $curtime;

EDIT2:我已经更正了,看看这段代码:

$date = new DateTime('2013-11-21');
$date->add(DateInterval::createFromDateString('5 days'));

$now = new DateTime('now');
$today = new DateTime(date('Y-m-d'));

$time = $today->diff($now);

$date->add($time);

echo $date->format('Y-m-d H:i:s');

EDIT3:请记住时区:

$date = new DateTime('2013-11-21', new DateTimeZone('Europe/Warsaw'));
$date->add(DateInterval::createFromDateString('5 days'));

$now = new DateTime('now', new DateTimeZone('Europe/Warsaw'));
$today = new DateTime(date('Y-m-d'), new DateTimeZone('Europe/Warsaw'));


$time = $today->diff($now);

$date->add($time);

echo $date->format('Y-m-d H:i:s');

小提琴:http://sandbox.onlinephpfunctions.com/code/0080d18d18dd7e2fefa7dea7d961087f14ceb3df

答案 1 :(得分:0)

您可以像这样添加5天:

 $nextX = time() + (5 * 24 * 60 * 60);

5天* 24小时* 60分钟* 60秒

答案 2 :(得分:0)

<强>尝试:

$date = '2013-11-21';
$date = strtotime($date);
$date = strtotime("+7 day", $date);
echo date('M d, Y', $date);

答案 3 :(得分:0)

试试这个

$hour_two = "2013-11-21";
$date = strtotime($hour_two);
$hour_two = $date  + (5 * 24 * 60 * 60);
$hour_two=date('Y-m-d',$hour_two);
$currenttime = date('H:i:s');
$h =  strtotime($currenttime);
$minute = date("i", $h);
$second = date("s", $h);
$hour = date("H", $h);
$new_time = $hour_two." ".$hour.":".$minute.":".$second;
echo $new_time."<br/>"; // here is your final date time
$timeto_string=strtotime($new_time);    // test using strtotime
echo date('Y-m-d H:i:s',$timeto_string);  // print by formating

答案 4 :(得分:0)

$curtime = date('H:i:s');
$date = @date("Y-m-d H:i:s",strtotime($mydate.$curtime)) ;