I have $adate;
which contains:
Tue Jan 4 07:59:59 2011
I want to add to this date the following:
$duration=674
When I need to implement some calculation, I always keep in mind what is it that I need. For example, if I need to add some seconds to a datetime, I need a datetime somewhere in the future. That is, I need a class called Future
. How is it identified? What data does it need to operate? It seems that there should be at least two values: a datetime relative to which I need a future date, and an interval which defines a time distance between start datetime and desired datetime.
So here is a code:
use Meringue\ISO8601DateTime\FromISO8601 as DateTimeFromISO8601String;
$f =
new Future(
new DateTimeFromISO8601String('2011-01-04T07:59:59+00'),
new NSeconds(674165)
);
Then you can output it in ISO8601 format:
$f->value(); // returns 2011-01-12T03:16:04+00:00
If your initial datetime is not in ISO8601 format, which is the case in your example, you should create a datetime from a custom format, hence a name of the class -- FromCustomFormat
. Since it is a datetime which represents itself in ISO8601 format, it extends an abstract class called ISO8601DateTime
. Here is a complete example:
(new Future(
new FromCustomFormat(
'D M j H:i:s Y',
'Tue Jan 4 07:59:59 2011'
),
new NSeconds(674165)
))
->value();
Here is some more about this approach.
I made this example for a timezone, but if you change some parts it may help you out:
$seconds_to_add = 30;
$time = new DateTime();
$time->setTimezone(new DateTimeZone('Europe/London'));
$time2 = $time->format("Y/m/d G:i:s");
$time->add(new DateInterval('PT' . $seconds_to_add . 'S'));
$timestamp = $time->format("Y/m/d G:i:s");
echo $timestamp;
echo '========';
echo $time2;
Result:
2018/06/17 3:16:23========2018/06/17 3:15:53
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);
// add 20 sec to now
$duration = 20;
echo date("Y-m-d H:i:s", strtotime("+$duration sec"));
Do this:
$seconds = 1;
$date_now = "2016-06-02 00:00:00";
echo date("Y-m-d H:i:s", (strtotime(date($date_now)) + $seconds));
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);