2

I need to find the day difference from the date("YmdHis") value.let say one value is:

$previous_date='20101202115755';
$current_date= date("YmdHis");
$day_difference=?????

Now i need to find the only day difference between two values.Is their any kind heart who can help me to find the value?

ajreal
  • 46,720
  • 11
  • 89
  • 119
riad
  • 7,144
  • 22
  • 59
  • 70
  • If you want a nice readable difference like "1 day, five hours and 25 minutes", see my answer to this - http://stackoverflow.com/questions/4394161/php-time-calculation/4394181#4394181 – El Yobo Dec 12 '10 at 11:46

4 Answers4

8

For PHP >= 5.3.0:

$prev = DateTime::createFromFormat("YmdHis", '20101202115755');
$curr = new DateTime();
$diff = $curr->diff($prev);
echo "Difference: ".$diff->days;
gnud
  • 77,584
  • 5
  • 64
  • 78
2

Just convert your dates to timestamps and then subtract previous_date from current_date and divide by number of seconds in a day. This is an example:

$day = 60*60*24;

$now = time();
$target = strtotime('2010-12-24');

$diff = round(($target - $now) / $day);
echo $diff;

If you want number of days in between, subtract $diff by one.

alexn
  • 57,867
  • 14
  • 111
  • 145
0

You have a strange format...

  1. Parse it to get a UNIX timestamp with strptime and mktime:

    $d = strptime($previous_date, '%Y%m%d%H%M%S');
    $prev_ts = mktime($d['tm_hour'], $d['tm_min'], $d['tm_sec'], $d['tm_mon'] + 1, $d['tm_mday'], $d['tm_year'] + 1900);
    
  2. Subtract the timestampes (time() gives the current time):

    $diff = time() - $prev_ts;
    
  3. Divide by 60*60*24 seconds to get the difference in days:

    $diff = floor($diff / (60*60*24)); // or round(), ceil() whatever fits best
    

That said, if possible try to store or get the date not as 20101202115755 but as UNIX timestamp. Then you don't have to go through the conversion hassle.

Working DEMO

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0
<?php
$previous_date="201012021157552";
$previous_date_as_time = mktime(
  substr($previous_date, 8, 2),
  substr($previous_date, 10, 2),
  substr($previous_date, 12, 2),
  substr($previous_date, 4, 2),
  substr($previous_date, 6, 2),
  substr($previous_date, 0, 4)
);

$days_between_dates = (time() - $previous_date_as_time) / 86400;

echo $days_between_dates;
?>
thedom
  • 2,498
  • 20
  • 26
  • You should add a call to either `floor()` or `round()` during the assignment to `$days_between_dates`, depending on your preference, otherwise you'll very likely get long floats back. – AgentConundrum Dec 12 '10 at 10:14
  • I know :). But I think that can be accomplished by riad like he wants it ;-). – thedom Dec 12 '10 at 10:15