简体   繁体   中英

Working dates between two given dates in Php

Please, i need assistance in this code.I have checked others in Stakeoverflow, but it is not combatible, hence this question. I want to generate all working /weekdays between two dates.I have found a code, but it is generating all days, including weekend. How do i eliminate the weekend from the list or ensure the list generated is ONLY for weekdays?

<?php

$start_Date = date('Y-m-d');
$end_Date = date('Y-m-d', strtotime('30 weekdays'));
//echo $start_Date."<br/>";
//echo $end_Date."<br/>";

// Specify the start date. This date can be any English textual format  
$date_from = $start_Date;
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp  

// Specify the end date. This date can be any English textual format  
$date_to = $end_Date;
$date_to = strtotime($date_to); // Convert date to a UNIX timestamp  

// Loop from the start date to end date and output all dates inbetween  
$c = 0;
for ($i = $date_from; $i <= $date_to; $i += 86400) {
    $c++;
    echo $c . "=> " . date("Y-m-d", $i) . '<br />';
}

I expect 30days to be generated but with this code, I am getting 42days . Weekend has been added,instead of weekdays ONLY .

Just add this to your loop:

$w = date('w',$i);// day of week - Sunday == 0, Saturday == 6
if($w == 0 || $w == 6){
    continue;
}

DEMO

You may need to get the day of the week, like date("D"), then use it in your for loop to check..something like this?:

$Weekends = array("Sat","Sun");
for....
    $DayOfWeek = date("D",$i);
    if(!in_array($DayOfWeek, $Weekend)){
        // increment...
    }

Your code is almost working only have to add a if checking in your code

your code

for ($i = $date_from; $i <= $date_to; $i += 86400) {
   $c++;
   echo $c . "=> " . date("Y-m-d", $i) . '<br />';
}

please replace with that one

for ($i = $date_from; $i <= $date_to; $i += 86400) {
    $day = date("w", $i);
    if($day != 0 && $day!= 6){ // will continue if not Sunday or Saturday
      $c++;
      echo $c . "=> " . date("Y-m-d", $i) . '<br />';
    }
}

You also can take help from php.net

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM