How to calculate the number of working days between two dates

We have a PHP-based scheduling system that was developed in the house and developed over the years, however, one part of the information presented to users is the number of working days left in each project.

Currently, I just take the difference between the current date and the end date of the project and dividing by 7 and multiplying by 5. This was enough for a long time and mostly accurate enough for employees who work full time from Monday to Friday. However, now we have several employees who work only with an odd day a week.

The scheduling system knows what days the staff work, this information is stored in a line in the user class, for working time it is a full day, the value will be NNYYYYY(which means ssMTWTF).

I could very easily make the result more accurate by dividing the difference between the two dates by seven, and then multiplying by the number of days during which they work, but by making this change, I am considering creating a much more accurate means of calculating the real value.

The easiest way that comes to mind is simply to use a cycle between two dates, comparing the day of the week with the user's work template, adding it to the counter on the days when the user is working on that day.

Given that this calculation should be performed on average about 30 times on the watch page due to the number of projects on the schedule, and projects can span 12 or 18 months at a time (which is a lot of cycles for each page load), I wonder if there is a more efficient way to do it in php?

+4
source share
5 answers

Maybe this piece of code will help:

<?php
//get current month for example
$beginday = date("Y-m-01");
$lastday  = date("Y-m-t");

$nr_work_days = getWorkingDays($beginday, $lastday);
echo $nr_work_days;

function getWorkingDays($startDate, $endDate)
{
    $begin = strtotime($startDate);
    $end   = strtotime($endDate);
    if ($begin > $end) {
        echo "startdate is in the future! <br />";

        return 0;
    } else {
        $no_days  = 0;
        $weekends = 0;
        while ($begin <= $end) {
            $no_days++; // no of days in the given interval
            $what_day = date("N", $begin);
            if ($what_day > 5) { // 6 and 7 are weekend days
                $weekends++;
            };
            $begin += 86400; // +1 day
        };
        $working_days = $no_days - $weekends;

        return $working_days;
    }
}

Another solution might be: Get a date range between two dates, excluding weekends

+9
source

You can find the number of working days using the following function.

Here you can see LIVE DEMO .

function number_of_working_days($startDate, $endDate)
{
    $workingDays = 0;
    $startTimestamp = strtotime($startDate);
    $endTimestamp = strtotime($endDate);
    for ($i = $startTimestamp; $i <= $endTimestamp; $i = $i + (60 * 60 * 24)) {
        if (date("N", $i) <= 5) $workingDays = $workingDays + 1;
    }
    return $workingDays;
}
+2
source

" ".

        $startDate = '2016-10-01';
        $endDate =  '2016-10-31';
        $weekdays = array('1','2','3','4','5','6'); //this i think monday-saturday

        $begin = new DateTime($startDate);
        $end = new DateTime($endDate);

        $end = $end->modify( '+1 day' ); //add one day so as to include the end date of our range

        $interval = new DateInterval('P1D'); // 1 Day
        $dateRange = new DatePeriod($begin, $interval, $end);

        $total_days = 0;
        //this will calculate total days from monday to saturday in above date range
        foreach ($dateRange as $date) {

         if (in_array($date->format("N"),$weekdays)) {
                $total_days++; 
          }
        }
+1

I tried some of the solutions and they did not work for me (gave me the result, including the weekend), so I wrote this as a solution:

function number_of_working_days($from, $to) {
    $target = strtotime($from);
    $days = 0;  
    while ($target < strtotime(date("Y-m-d",strtotime($to)))) {
        if(date("N",$target) <= 5) $days++;
        $target += (60*60*24);  /* move forward by 1 day */
    }
    return $days;
}

Where $fromand $toare dates from the mySQL table.

0
source
function workingDaysBetweenDates(startDate, endDate) {

    // Validate input
    if (endDate < startDate)
        return 0;

    // Calculate days between dates
    var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
    startDate.setHours(0,0,0,1);  // Start just after midnight
    endDate.setHours(23,59,59,999);  // End just before midnight
    var diff = endDate - startDate;  // Milliseconds between datetime objects    
    var days = Math.ceil(diff / millisecondsPerDay);

    // Subtract two weekend days for every week in between
    var weeks = Math.floor(days / 7);
    days = days - (weeks * 2);

    // Handle special cases
    var startDay = startDate.getDay();
    var endDay = endDate.getDay();

    // Remove weekend not previously removed.   
    if (startDay - endDay > 1)         
        days = days - 2;      

    // Remove start day if span starts on Sunday but ends before Saturday
    if (startDay == 0 && endDay != 6) {
        days = days - 1;  
    }

    // Remove end day if span ends on Saturday but starts after Sunday
    if (endDay == 6 && startDay != 0) {
        days = days - 1;
    }

    return days;
}

$('#results').html(workingDaysBetweenDates(new Date('6/03/2019'), new Date('6/17/2019')));

Hope this helps.

0
source

Source: https://habr.com/ru/post/1539107/


All Articles