1

I want to do is to count the days between two dates excluding the weekends and i;m done doing that using the function below. But whenever the $startDate is greater than the $endDate i can't get the proper result. I try to use if ($startDate>$endDate) and i'm stock with that condition and honestly don't know what is the next step.

function getWorkingDays($startDate,$endDate){
        // do strtotime calculations just once
        $startDate = strtotime($startDate);
        $endDate = strtotime($endDate);

        //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
        //We add one to inlude both dates in the interval.
        $days = ($endDate - $startDate) / 86400 + 0;

        $no_full_weeks = floor($days / 7);
        $no_remaining_days = fmod($days, 7);

        //It will return 1 if it's Monday,.. ,7 for Sunday
        $the_first_day_of_week = date("N", $startDate);
        $the_last_day_of_week = date("N", $endDate);

        // If one of the value is empty it will return "0"
         if ($startDate == '' || $endDate == '')
                return "0"; // Default value

        //---->The two can be equal in leap years when february has 29 days, the equal sign is added here
        //In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
        if ($the_first_day_of_week <= $the_last_day_of_week) {
            if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
            if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
        }
        else {
            // (edit by Tokes to fix an edge case where the start day was a Sunday
            // and the end day was NOT a Saturday)

            // the day of the week for start is later than the day of the week for end
            if ($the_first_day_of_week == 7) {
                // if the start date is a Sunday, then we definitely subtract 1 day
                $no_remaining_days--;

                if ($the_last_day_of_week == 6) {
                    // if the end date is a Saturday, then we subtract another day
                    $no_remaining_days--;
                }
            }
            else {
                // the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
                // so we skip an entire weekend and subtract 2 days
                $no_remaining_days -= 2;
            }
        }

        //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
        //---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
        $workingDays = $no_full_weeks * 5;
        if ($no_remaining_days > 0 )
        {
          $workingDays += $no_remaining_days;
        }

        return $workingDays;
    }
kardo
  • 35
  • 1
  • 7

6 Answers6

3
$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");

$timeDiff = abs($endTimeStamp - $startTimeStamp);

$numberDays = $timeDiff/86400;  // 86400 seconds in one day

// and you might want to convert to integer
$numberDays = intval($numberDays);

OR

function dateDiff($start, $end) {
  $start_ts = strtotime($start);
  $end_ts = strtotime($end);
  $diff = $end_ts - $start_ts;
  return round($diff / 86400);
}
echo dateDiff("2011-02-15", "2012-01-16").'days';

//Get number of days deference between current date and given date.
echo dateDiff("2011-02-15", date('Y-m-d')).'days';  

For Count days excluding use below code

$start = new DateTime('7/17/2017');
$end = new DateTime('7/24/2017');
$oneday = new DateInterval("P1D");
$daysName = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri');
$days = array();
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
    $day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
    if($day_num < 6) { /* weekday */

        $days[$day->format("Y-m-d")] = date('D', strtotime($day->format("Y-m-d")));;
    } 
} 
echo "<pre>";
print_r($days);   
echo count($days);
  • The codes is great, But it's not excluding the weekends. – kardo Jul 21 '17 at 12:34
  • 1
    *..But it's not excluding the weekends.* In Question, Where You Mentioned About It? @kardo – Nana Partykar Jul 21 '17 at 12:39
  • sorry for not mentioning "excluding the weekends", the updated code that you been given is great it exclude the weekends. However, if the $start is greater than $end i can't get the proper result. – kardo Jul 22 '17 at 04:41
2

This will check whether start date is less than end date. If yes, then it will display the days.

<?php

if($days = getWorkingDays("2017-05-01","2018-01-01")){
  echo $days;
}

function getWorkingDays($startDate,$endDate){
  $startDate = strtotime($startDate);
  $endDate = strtotime($endDate);

  if($startDate <= $endDate){
    $datediff = $endDate - $startDate;
    return floor($datediff / (60 * 60 * 24));
  }
  return false;
}
?>

Output: 245

Functions Used:

  1. strtotime(): The strtotime() function parses an English textual datetime into a Unix timestamp
  2. floor(): The floor() function rounds a number DOWN to the nearest integer

Edit-1: Getting Days After Excluding Weekends (saturdays & sundays)

//getWorkingDays(start_date, end_date)
if($days = getWorkingDays("2017-05-01","2018-01-01")){
      echo $days;
}

function getWorkingDays($startDate,$endDate){

  $days = false;
  $startDate = strtotime($startDate);
  $endDate = strtotime($endDate);

  if($startDate <= $endDate){
    $datediff = $endDate - $startDate;
    $days = floor($datediff / (60 * 60 * 24)); // Total Nos Of Days

    $sundays = intval($days / 7) + (date('N', $startDate) + $days % 7 >= 7); // Total Nos Of Sundays Between Start Date & End Date
    $saturdays = intval($days / 7) + (date('N', $startDate) + $days % 6 >= 6); // Total Nos Of Saturdays Between Start Date & End Date

    $days = $days - ($sundays + $saturdays); // Total Nos Of Days Excluding Weekends
  }
  return $days;
}
?>

Sources:

  1. calculate sundays between two dates
  2. The intval() function is used to get the integer value of a variable.
  3. See Description date('N', $date) : N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
  • Hi @Nana Partykar! Thanks for the answer, sorry for not mentioning the "Excluding the weekends" but i already edit my question. you can see my quesstion again. Thanks! – kardo Jul 22 '17 at 04:54
  • @kardo: I've updated my answer. Now, it will exclude weekend (saturdays and sundays). Please Go Through [**Edit-1**](https://stackoverflow.com/questions/45237577/count-the-days-between-two-dates/45237777#45237777) section of mine. – Nana Partykar Jul 22 '17 at 12:45
  • How can i get the proper result if the $startDate has a value greater than $endDate? because whenever i do that sometimes i get result of none. so i try to create a condition in function "if($startDate>$endDate)" and i dont know what is the next step. – kardo Jul 23 '17 at 03:28
  • *"..How can i get the proper result if the $startDate has a value greater than $endDate?"* What Result You Want In This Scenario? @kardo – Nana Partykar Jul 23 '17 at 08:13
  • Example my $startDate has a value of (2017-04-17) and my $endDate is (2017-04-21) and my result is 4 which right, But if the $startDate is (2017-04-21)and $endDate is (2017-04-17) i got the result of -5, even the $endDate is(2017-04-16) i still got -5. @Nana Partykar – kardo Jul 23 '17 at 10:11
1

There is the script of code for do this.

<?php

  $now = time(); // or your date as well 
  $your_date = strtotime("2010-01-01");
  $datediff = $now - $your_date;

  echo floor($datediff / (60 * 60 * 24));
?>

or

 $datetime1 = new DateTime("2010-06-20");

 $datetime2 = new DateTime("2011-06-22");

 $difference = $datetime1->diff($datetime2);

 echo 'Difference: '.$difference->y.' years, ' 
               .$difference->m.' months, ' 
               .$difference->d.' days';

 print_r($difference);
Anand Pandey
  • 2,025
  • 3
  • 20
  • 39
1

EDIT: I noticed in the comment you want to exclude the weekend day/days (however you didn't mention that in your post !) you can add the number of days you want to exclude from the week

you can use DateTime::diff and use the option for absolute result (positive difference always)

<?php
function daysBetween2Dates($date1, $date2, $execludedDaysFromWeek = 0)
{
    try{
        $datetime1 = new \DateTime($date1);
        $datetime2 = new \DateTime($date2);
    }catch (\Exception $e){
        return false;
    }
    $interval = $datetime1->diff($datetime2,true);
    $days = $interval->format('%a');
    if($execludedDaysFromWeek < 0 || $execludedDaysFromWeek > 7){
        $execludedDaysFromWeek = 0 ;
    }
    return ceil($days * (7-$execludedDaysFromWeek) / 7);
}

Usage Example

// example 1 : without weekend days, start date is the first one
$days = daysBetween2Dates('2016-12-31','2017-12-31');
echo $days;
// example 2 : without weekend days, start date is the second one
$days = daysBetween2Dates('2017-12-31', '2016-12-31');
echo  "<br>\n" .$days;
// example 3 : with weekend days, it returns 6 days for the week
$days = daysBetween2Dates('2017-12-31', '2017-12-24',-1);
echo  "<br>\n" .$days;
exit;

this outputs

365
365
6

live demo (https://eval.in/835862)

Accountant م
  • 6,975
  • 3
  • 41
  • 61
1

try this

public function datediff($sdate,$edate){

    $diffformat='%a';
    $date1              = date_create($sdate);
    $date2              = date_create($edate);
    $diff12             = date_diff($date2, $date1);
    $days               = $diff12->format($diffformat) + 1;}
0

use date_diff() which returns the difference between two DateTime objects.

$diff=date_diff($startDate,$endDate);
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70