Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: add seconds to a date

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.

like image 950
ADM Avatar asked Dec 27 '10 12:12

ADM


People also ask

How to add DateTime in PHP?

The DateTime::add() function is an inbuilt function in PHP which is used to add an amount of time (days, months, years, hours, minutes and seconds) to the given DateTime object.

How can I compare two dates in if condition in PHP?

Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format. Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates. echo "$date1 is older than $date2" ; ?>


2 Answers

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(); ?> 
like image 160
Elzo Valugi Avatar answered Sep 19 '22 08:09

Elzo Valugi


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); 
like image 20
DiglettPotato Avatar answered Sep 22 '22 08:09

DiglettPotato