简体   繁体   English

在PHP中两个给定日期之间的工作日期

[英]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. 请在此代码中我需要帮助。我已经在Stakeoverflow中检查了其他人,但是它不易操作,因此是这个问题。 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 . 我希望可以生成30天,但是使用此代码,我可以得到42天。 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 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?: 您可能需要获取星期几,例如date(“ D”),然后在for循环中使用它来检查..类似这样的东西:

$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 您也可以从php.net获取帮助

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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