0

I need to know how many days are involved in a date diff. \For example:

<?

$start = new DateTime('2014-06-29 14:00:00');
$ende = new DateTime('2014-07-02 05:45:00');

$diff = $start->diff($ende);

echo $diff->format('%R');
echo $diff->days;
?>

The above code echos +2

My desired result would be 4, because the 29th, 30th, 1st and 2nd of July are "touched". I have no idea to achieve that with the given functions. Coding a day-subtraction seems to bean open door for errors.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103

3 Answers3

0

PHP never seems to include the last day when doing diffs or working with DatePeriods. In your case, if time is not a factor, just remove the times from each date and then add one day to the last date. Then that last day will be the one ignored and an accurate result will be achieved.

<?php

$start = new DateTime('2014-06-29');
$ende = (new DateTime('2014-07-02'))->modify('+1 day');
$diff = $start->diff($ende);

echo $diff->format('%R');
echo $diff->days;
?>

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Well infact time is a factor, because the times are in UTC, but the days are relevant in local times which means, that $ende = "2014-07-02 23:00" would be the 3rd in local time already. So taking the time-tag off is not an option. Any further ideas? – user3549835 May 31 '14 at 13:56
0

If you think about it, you are getting the correct answer.

start is 2014-06-29 14:00:00

1 day's difference would be 2014-06-30 14:00:00

2 day's difference would be 2014-07-01 14:00:00

3 day's difference would be 2014-07-02 14:00:00

4 day's difference would be 2014-07-03 14:00:00

your end date is 2014-07-02 05:45:00 which would be 2days 15hours and 45minutes so showing just the days difference the answer would be 2.

At no point would the answer be 4 days.

EDIT/UPDATE:

Well this gives the answer 4!

<?php
    $start = strtotime('2014-06-29');
    $end = strtotime('2014-07-02');

    $diff = $end - $start;

    echo 'DAYS DIFF = ' . date('d', $diff) . PHP_EOL;

But this does not it gives 3 as of course thats the correct answer.

<?php
    $start = strtotime('2014-06-29 14:00:00');
    $end = strtotime('2014-07-02 05:45:00');

    $diff = $end - $start;

    echo 'DAYS DIFF = ' . date('d', $diff) . PHP_EOL;

So if you want the answer 4 it look like you are going to have to remove the time portion of your data/time field.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • I'm not saying that the difference is wrong. I'm just saying that it is not the answer I need. So do you have an idea how I get to the answer to my question? – user3549835 May 31 '14 at 14:20
0

Try this:

$start = new DateTime('2014-06-29 14:00:00');
$ende = new DateTime('2014-07-02 05:45:00');
$start->setTime(0, 0);
$ende ->setTime(0, 0);
$diff = date_diff($start, $ende);
echo $diff->format('%R%a')+1;

"+1" because difference between days less by one.

GR Vitaly
  • 58
  • 7