PHP如何计算两个日期之间的工作日数?

2021年3月20日16:07:02 发表评论 892 次浏览

给你两个表示两个日期的字符串(dd-mm-yyyy), 你必须查找给定日期之间存在的所有工作日数。

例子:

Input : startDate = "01-01-2018"   endDate = "01-03-2018"
Output : Array
(
    [Monday] => 9
    [Tuesday] => 9
    [Wednesday] => 9
    [Thursday] => 9
    [Friday] => 8
    [Saturday] => 8
    [Sunday] => 8
)

Input : startDate = "01-01-2018"   endDate = "01-01-2018"
Output : Array
(
    [Monday] => 1
    [Tuesday] => 0
    [Wednesday] => 0
    [Thursday] => 0
    [Friday] => 0
    [Saturday] => 0
    [Sunday] => 0
)

找出所有工作日数的基本思想很简单, 你必须从开始日期到结束日期进行迭代, 并增加每一天的计数。因此, 你可以计算所需的结果。

在php中, 我们可以通过使用date()函数来查找特定日期的日期为日期(" l", $ timestamp)其中$ timestamp是strtotime($ date)。你也可以借助以下方法将日期值增加1$ date-> modify(" + 1天").

算法:

convert startDate & endDate string into Datetime() object. 
    Iterate from startDate to endDate in a loop:
    
      Find out then  timestamp of startDate. 
     Find out the weekday for current timestamp of startDate. 
     Increase the value of particular weekday by 1. 
     Increase the value of startDate by 1. 
    
   Print the array containing value of all weekdays.
<?php
     // input start and end date
     $startDate = "01-01-2018" ;
     $endDate = "01-01-2019" ;
      
     $resultDays = array ( 'Monday' => 0, 'Tuesday' => 0, 'Wednesday' => 0, 'Thursday' => 0, 'Friday' => 0, 'Saturday' => 0, 'Sunday' => 0);
  
     // change string to date time object
     $startDate = new DateTime( $startDate );
     $endDate = new DateTime( $endDate );
  
     // iterate over start to end date
     while ( $startDate <= $endDate ){
         // find the timestamp value of start date
         $timestamp = strtotime ( $startDate ->format( 'd-m-Y' ));
  
         // find out the day for timestamp and increase particular day
         $weekDay = date ( 'l' , $timestamp );
         $resultDays [ $weekDay ] = $resultDays [ $weekDay ] + 1;
  
         // increase startDate by 1
         $startDate ->modify( '+1 day' );
     }
  
     // print the result
     print_r( $resultDays );
?>

输出:

Array
(
    [Monday] => 53
    [Tuesday] => 53
    [Wednesday] => 52
    [Thursday] => 52
    [Friday] => 52
    [Saturday] => 52
    [Sunday] => 52
)

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: