2

Possible Duplicate:
How to calculate the difference between two dates using PHP?

enter image description here

$begintime=strtotime("2012-12-19");
$endtime=strtotime("2013-02-22");

The result should be;

array(
array('text'=>'12/2012','days'=>13),
array('text'=>'01/2013','days'=>31)
array('text'=>'02/2013','days'=>22)
)
Community
  • 1
  • 1
Mert Emir
  • 691
  • 1
  • 8
  • 20

2 Answers2

4

I prefer to work it in Object-oriented approach.

$begintime = new DateTime('2012-12-19'); // always use single quote whenever possible
$endtime = new DateTime('2013-01-22');
$time_interval = $endtime->diff($begintime); // in DateInterval object format

echo 'the time interval will be: ' . $time_interval->format('%d') . ' days';

For the conversion to Array format you suggested, please work it on your own. ( not the focus of the question, I think )

Raptor
  • 53,206
  • 45
  • 230
  • 366
3

For getting the days, try this:

$begintime = '2012-12-19';
$endtime = '2013-02-22';
$bd = new DateTime($begintime);
$ed = new DateTime($endtime);

$c = $bd->format('t') - $bd->format('d') + 1;
$pass = false;

while($bd->format('Y') < $ed->format('Y')
        || $bd->format('n') < $ed->format('n')) {
    $bd->modify("+1 month");
    echo $c." ";
    $c = $bd->format('t');
    $pass = true;
}
$c = $ed->format('d');
if(!$pass)
    $c -= $bd->format('d') - 1;
echo $c;

See http://ideone.com/07wqkp

$bd->format('t') gives the maximum number of days in a month.

ideone uses PHP 5.2.11. I suppose with PHP 5.4 you could use

$bd->add(new DateInterval("P1M"));

instead of $bd->modify("+1 month");.

EDIT: Fixed bug when starting and ending in the same month and year.

EDIT: Reverted to explicit comparisons. On second thought, it's better without the if/else.

irrelephant
  • 4,091
  • 2
  • 25
  • 41