1

I am trying to write a function that can count the number of days between 2 dates. I currently have the below but it is giving me some unexpected results:

function dayCount($from, $to) {
    $first_date = strtotime($from);
    $second_date = strtotime($to);
    $offset = $second_date-$first_date; 
    return floor($offset/60/60/24);
}

print dayCount($s, $e).' Days';

A couple of correct examples:

$s = '18-03-2016';
$e = '25-03-2016';

Outputs: 7 Days - correct

$s = '03-02-2016';
$e = '06-02-2016';

Outputs: 3 Days - correct

$s = '06-04-2016';
$e = '27-04-2016';

Outputs: 21 Days - correct

But when I have dates that cross over between 2 months sometimes it is correct, sometimes it shows a day less:

$s = '25-03-2016';
$e = '01-04-2016';

Outputs: 6 Days - should be 7 Days

$s = '23-02-2016';
$e = '01-03-2016';

Outputs: 7 Days - correct

3
  • 4
    Why not use date_diff PHP function? Commented Jan 4, 2016 at 12:00
  • duplicate of stackoverflow.com/questions/33732686/… Commented Jan 4, 2016 at 12:12
  • It's not the "cross over between 2 months" that's causing the issue. The issue is intervals starting on or before '27-03-2016' and ending on or after '28-03-2016'. March 27, 2016 is the start of Daylight Saving Time (in the EU). When calculating a difference in seconds between two timestamps, from strings with different timezone offsets... in a timezone that observes DST, there's only 23 hours in March 27, 2016. Commented Jan 8, 2016 at 21:33

3 Answers 3

10

Please use diff function for get days between two date.

$date1 = new DateTime("25-03-2016");
$date2 = new DateTime("01-04-2016");

echo $diff = $date2->diff($date1)->format("%a");
Sign up to request clarification or add additional context in comments.

Comments

6

please use date_diff function like this

<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>

hope this helps you thanx.

1 Comment

Plus one for taking negative numbers in to account
3

You can also use this (for versions PHP 5.1.5 and above without using date_diff()):

function dayCount($from, $to) {
    $first_date = strtotime($from);
    $second_date = strtotime($to);
    $days_diff = $second_date - $first_date;
    return date('d',$days_diff);
}

print dayCount($s, $e).' Days';

1 Comment

No leading 0 return date('j',$days_diff);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.