Asked  7 Months ago    Answers:  5   Viewed   37 times

Possible Duplicates:
Number of seconds from now() to Sunday midnight
Calculates difference between two dates in PHP

Hello All,

In my project, I need to calculate the difference in seconds between two dates:

For Example :

$firstDay = "2011-05-12 18:20:20";
$secondDay = "2011-05-13 18:20:20";

Then I should get 86400 Seconds That is 24 hours.

Similarly For

$firstDay = "2011-05-13 11:59:20";
$secondDay = "2011-05-13 12:00:20";

It should return 60 Seconds.

I read lots of questions in the stackoverflow But they only deals with the difference between 2 minute fields like 11:50:01 and 12:10:57

 Answers

50
$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Wednesday, March 31, 2021
 
PLPeeters
answered 7 Months ago
96

You could also take a look at the DatePeriod class:

$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')
);

Which should get you an array with DateTime objects.

To iterate

foreach ($period as $key => $value) {
    //$value->format('Y-m-d')       
}
Wednesday, March 31, 2021
 
CAMason
answered 7 Months ago
68
 SELECT julianday('now') - julianday(DateCreated) FROM Payment;
Wednesday, June 9, 2021
 
muaaz
answered 5 Months ago
24

You need to call DateInterval::format() to display that difference as a string.

echo $diff->format('%d days');

See the manual for all of the available formatting options.

Wednesday, July 7, 2021
 
mattltm
answered 4 Months ago
100

You can turn a date object into a long (milliseconds since Jan 1, 1970), and then use TimeUnit to get the number of seconds:

long diffInMs = endDate.getTime() - startDate.getTime();

long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);

Edit: -Corrected the name of the variable diffInMs which was written diffInM(i)s in the second line.

Sunday, August 8, 2021
 
RenegadeAndy
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :