Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting two dates in php

Tags:

php

I have got two dates in php

$date1 = 'May 3, 2012 10:38:22 GMT'  $date2 = '06 Apr 2012 07:22:21 GMT' 

Then I subtract both of them

$date2 - $date1 

, and get

Result:6 

Why is the result 6 and not 27? ... ? How can I subtract the two dates, and make it return me a result based on month differences while subtracting the years & days & time ?

like image 766
Dmitry Makovetskiyd Avatar asked May 06 '12 07:05

Dmitry Makovetskiyd


People also ask

Can I subtract dates in php?

The date_sub() function subtracts some days, months, years, hours, minutes, and seconds from a date.

How can I get second date between two dates in php?

Show activity on this post. $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.

How can I get the number of days between two given dates in php?

The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.


2 Answers

Part 1: Why is the result 6?

The dates are simply strings when you first subtract them. PHP attempts to convert them to integers. It does this by converting until the first non-number. So, date2 become 6 and date1 becomes 0.

Part 2: How do you get it to work?

$datetime1 = strtotime('May 3, 2012 10:38:22 GMT'); $datetime2 = strtotime('06 Apr 2012 07:22:21 GMT');  $secs = $datetime2 - $datetime1;// == <seconds between the two times> $days = $secs / 86400; 

Convert as appropriate.

like image 170
evan Avatar answered Sep 28 '22 21:09

evan


Using DateTime and DateInterval,

$date1 = new DateTime("May 3, 2012 10:38:22 GMT"); $date2 = new DateTime("06 Apr 2012 07:22:21 GMT"); echo $date1->diff($date2)->format("%d"); 
like image 43
Shiplu Mokaddim Avatar answered Sep 28 '22 21:09

Shiplu Mokaddim