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 ?
The date_sub() function subtracts some days, months, years, hours, minutes, and seconds from a date.
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With