1

Possible Duplicate:
How to count days between two dates in PHP?

Seems there's only a javascript version,what about in PHP?

Community
  • 1
  • 1
DriverBoy
  • 937
  • 1
  • 11
  • 23
  • @Shakti Singh ,my question is to count between `today` and another day,so a little different.. – DriverBoy May 20 '11 at 07:50
  • 2
    No diff at all. get today date by `date('Y-m-d')` function – Shakti Singh May 20 '11 at 07:51
  • Possible Duplicate: answer [How to count days between two dates in PHP?](http://stackoverflow.com/questions/3653882/how-to-count-days-between-two-dates-in-php) – Harsh May 20 '11 at 07:56

4 Answers4

2

Taken almost directly from an article I wrote a few weeks ago: Working with Date and Time in PHP

$today = new DateTime();
$ref = new DateTime("2011-05-20");

$diff = $today->diff($ref);
echo "the difference is {$diff->days} days" . PHP_EOL;
James C
  • 14,047
  • 1
  • 34
  • 43
0

Calculate the seconds they differ, and you can easily calculate the amount of days.

$oFirstDate = new DateTime($sDateFormat);
$oSecondDate = new DateTime($sDateFormat2);
$iSeconds = $oFirstDate->getTimeStamp() - $oSecondDate->getTimeStamp();
$iDays = $iSeconds / 60 / 60 / 24;
Wesley van Opdorp
  • 14,888
  • 4
  • 41
  • 59
0

I do agree with Shakti; with minimal changes, the script from the other question will work for you:

<?php
$datetime1 = date_create( date( 'Y-m-d' ) );
$datetime2 = date_create('2011-05-21');
$interval = date_diff($datetime1, $datetime2);

echo $interval->days . " days difference.";
Community
  • 1
  • 1
Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
0

Well, I have a generic-ish function for stuff like that:

function timediffIn($time, $unit, $human = False){

    $tokens = array (
        'years'   => 31536000,
        'months'  => 2592000,
        'weeks'   => 604800,
        'days'    => 86400,
        'hours'   => 3600,
        'minutes' => 60,
        'seconds' => 1
    );

    if(!array_key_exists($unit, $tokens)){
        if ($human) print "No such unit: $unit\n";
        return FALSE;   
    } 
    if(!strtotime($time)){
        if ($human) print "$time does not translate into a valid time\n";
        return FALSE;
    }

    $elapsed = time() - strtotime($time);

    $interval = $tokens[$unit];
    if($human){
        print "It has been " . floor($elapsed / $interval) . " $unit since $time\n";
    }
    return floor($elapsed / $interval);

}

HTH

Wagemage
  • 300
  • 1
  • 4
  • 10
  • Obviously, the "human" parameter is for debug purposes / command line scripts - you can safely strip out everything concerning it. – Wagemage May 20 '11 at 08:04