PHP: add seconds to a date

2019-01-19 09:36发布

I have $adate; which contains:

Tue Jan 4 07:59:59 2011

I want to add to this date the following:

$duration=674165; // in seconds

Once the seconds are added I need the result back into date format.

I don't know what I'm doing, but I am getting odd results.

Note: both variables are dynamic. Now they are equal to the values given, but next query they will have different values.

9条回答
不美不萌又怎样
2楼-- · 2019-01-19 10:20

Just use some nice PHP date/time functions:

$adate="Tue Jan 4 07:59:59 2011";
$duration=674165;
$dateinsec=strtotime($adate);
$newdate=$dateinsec+$duration;
echo date('D M H:i:s Y',$newdate);
查看更多
做个烂人
3楼-- · 2019-01-19 10:21

Given the fact that $adate is a timestamp (if that's the case), you could do something like this:

$duration = 674165;
$result_date = strtotime(sprintf('+%d seconds', $duration), $adate);
echo date('Y-m-d H:i:s', $result_date);
查看更多
forever°为你锁心
4楼-- · 2019-01-19 10:24

If you are using php 5.3+ you can use a new way to do it.

<?php 
$date = new DateTime();
echo $date->getTimestamp(). "<br>";
$date->add(new DateInterval('PT674165S')); // adds 674165 secs
echo $date->getTimestamp();
?>
查看更多
登录 后发表回答