0

I will ask the user to enter start date and end date. I would want to get all of the dates from start to end and get the number of days between those dates. How can I do this in PHP given start and end date.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
anonymous
  • 1
  • 1
  • http://stackoverflow.com/questions/676824/how-to-calculate-the-date-difference-between-2-dates-using-php – ArK Dec 03 '10 at 07:47
  • http://stackoverflow.com/questions/3028491/php-weeks-between-2-dates – ArK Dec 03 '10 at 07:48
  • http://stackoverflow.com/questions/4312439/php-return-all-dates-between-two-dates-in-an-array – ArK Dec 03 '10 at 07:49

5 Answers5

0

When dealing with dates, you can convert to timestamps (seconds) as Ignacio recommends. But generally if possible you will be better off working with actual dates & days at a higher level.

For this, see the DateTime class built into PHP:

http://www.php.net/manual/en/class.datetime.php

http://www.php.net/manual/en/class.dateinterval.php

These are well supported in PHP 5.2, but PHP 5.3 adds even better DateTime handling functionality.

dkamins
  • 21,450
  • 7
  • 55
  • 59
0

End result of this code will be number of days.

$days = (strtotime(date("Y-m-d"))-strtotime("2010-08-20")) / (60 * 60 * 24); echo $days;

Adeel
  • 605
  • 1
  • 6
  • 16
0

Read my answer to this topic, with examples:

Calculate number of hours between 2 dates in PHP

Community
  • 1
  • 1
Fidi
  • 5,754
  • 1
  • 18
  • 25
0

Depending on the input the user gives, I would most likely be using something like

$dateOne = (int)(mktime(0, 0, 0, $month1, $day1, $year1)/86400); //Get the first date as a unix timestamp, then convert to days.
$dateTwo = (int)(mktime(0, 0, 0, $month2, $day2, $year2)/86400); //Get the second date as a unix timestamp, then convert to days.

// Example
//$dateOne = (int)(mktime(0,0,0,12,03,2009)/86400);
//$dateTwo = (int)(mktime(0,0,0,08,19,2011)/86400);

$daysBetween = $dateTwo-$dateOne; //Calculate days between.

echo $daysBetween.'<br />'; //Echo the days between.

for ($i=1; $i=$daysBetween; $i++) { //Loop through every day between, echo the date of that day.
    echo date('Y-m-d', $dateOne*86400+($i*86400)).'<br />';
}

The above code will give you all the days, including the first and last date. To get only the ones in between change:

for ($i=1; $i=$daysBetween; $i++) { //Loop through every day between, echo the date of that day.

to:

for ($i=2; $i<=$daysBetween; $i++) { //Loop through every day between, echo the date of that day.

Have tested, works well.

NOTE: the first date MUST be before the last date.

Cheers Charlie

Charlie Sheather
  • 2,374
  • 6
  • 20
  • 21
-1

Convert both dates to timestamps, then count from one to the other, converting back to dates.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358