0

I start with two dates:

$endDate   = '2013-11-30 18:30:00';
$beginDate = '2013-10-31 18:30:00';

Then, I took date difference using following code:

$diff = abs(strtotime($endDate) - strtotime($beginDate));

Next, I check the date difference by

$days = $diff / (60*60*24);

However, it returns a fractional day, such as 30.041666666667. I don't want to get this fractional. Why this happening? This problem occurs in some cases only.

gloomy.penguin
  • 5,833
  • 6
  • 33
  • 59
Ammu
  • 138
  • 3
  • 12
  • That's working exactly how you wrote it. You can either format the output or use [`floor()`](http://php.net/manual/en/function.floor.php) to get just the `30`. – gloomy.penguin Dec 04 '13 at 07:58
  • You can also use this SO post about [calculating relative time](http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time) (such as "2 days ago"). It is for `C#` but the logic is very easy to put in `PHP` syntax. – gloomy.penguin Dec 04 '13 at 08:01

2 Answers2

1

Try this :

$date1 = new DateTime("2013-11-21 12:59:00");
    $date2 = new DateTime("2013-11-21 13:01:00");
    $interval = $date1->diff($date2); 

    echo "DIFF: ".$interval->format("%Y-%m-%d %H:%i:%s");

Visit the link for details

Mahmood Rehman
  • 4,303
  • 7
  • 39
  • 76
1

you can also use mktime() function for calculate diff.

<?php
$endDate   = '2013-11-30 18:30:00';
$endDateTemp = explode(' ', $endDate);
$endDateArr1 = explode('-', $endDateTemp[0]);
$endDateArr2 = explode(':', $endDateTemp[1]);
$endTimestamp = mktime($endDateArr2[0], $endDateArr2[1], $endDateArr2[2], $endDateArr1[1], $endDateArr1[2], $endDateArr1[0]);
$beginDate = '2013-10-31 18:30:00';
$beginDateTemp = explode(' ', $beginDate);
$beginDateArr1 = explode('-', $beginDateTemp[0]);
$beginDateArr2 = explode(':', $beginDateTemp[1]);
$beginTimestamp = mktime($beginDateArr2[0], $beginDateArr2[1], $beginDateArr2[2], $beginDateArr1[1], $beginDateArr1[2], $beginDateArr1[0]);
$diff = $endTimestamp - $beginTimestamp;
$day = $diff/(24*60*60);
?>
harry
  • 1,007
  • 2
  • 10
  • 19
  • you should add an example to your answer to make it more complete or link to the function documentation at least – gloomy.penguin Dec 04 '13 at 07:59
  • your edit to the question was rejected because it changed the actual question being asked. don't make modifications that turn someone else's post into something entirely different. – gloomy.penguin Dec 04 '13 at 08:07
  • how to use this mktime() ? can you give me an example from my question? – Ammu Dec 04 '13 at 08:47
  • but this also output a fractional date difference. I got an output of 30.041666666667. I need to get 30 days only. – Ammu Dec 04 '13 at 09:07