如何从文件中读取日期并将它们排除在日期范围内?

我编写了一个代码来排除两个日期之间的周末和节假日。但现在我想将假期包含在文件中并排除它们。


代码工作正常


 <?php


  $joiningdate= date_create($row['jdate']); // Fetching this from database

  $tdate = date('Y-m-d');

  $todaydate1=date_create($tdate);

  $todaydate1->modify('+1 day'); 

  $interval=date_diff($todaydate1,$joiningdate);

  $days = $interval->days;


  // creating an iterateable period of date (P1D equates to 1 day)

  $period = new DatePeriod($joiningdate, new DateInterval('P1D'), $todaydate1);


  // Storing holidays in a array to exclude

  $holidays = array('2019-01-15','2019-01-26','2019-03-04','2019-05-01','2019-08-15','2019-09-02','2019-10-02','2019-09-08', '2019-11-01');


  foreach($period as $dt) {

      $curr = $dt->format('D');


      // substract holidays

      if (in_array($dt->format('Y-m-d'), $holidays)) {

         $days--;

      }


      // substracting if Saturday or Sunday

      if ($curr == 'Sat' || $curr == 'Sun') {

          $days--;

      }

  }

  echo $days;

 ?>

我得到了预期的输出。但现在我需要将假期数组添加到文件中并排除它们。


波斯汪
浏览 128回答 2
2回答

慕妹3242003

创建一个 dates.json 文件并像这样粘贴您要排除的所有日期&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "dates" : [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "2019-05-01",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "2019-06-01"&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }在您的 php 中,将这些日期读取为$holidays = file_get_contents('dates.json');$holidays = json_decode($holidays, true);$holidays = $holidays['dates'];现在你的假期变量有两个日期。

慕的地8271018

<?php&nbsp;&nbsp; $joiningdate= date_create($row['jdate']); // Fetching this from database&nbsp; $tdate = date('Y-m-d');&nbsp; $todaydate1=date_create($tdate);&nbsp; $todaydate1->modify('+1 day');&nbsp;&nbsp; $interval=date_diff($todaydate1,$joiningdate);&nbsp; $days = $interval->days;&nbsp; // creating an iterateable period of date (P1D equates to 1 day)&nbsp; $period = new DatePeriod($joiningdate, new DateInterval('P1D'), $todaydate1);&nbsp; // Storing holidays in a array to exclude&nbsp; $holidays = array('2019-01-15','2019-01-26','2019-03-04','2019-05-01','2019-08-15','2019-09-02','2019-10-02','2019-09-08', '2019-11-01');$return_data_set=array();&nbsp; foreach($period as $dt) {&nbsp; &nbsp; $curr = $dt->format('D');&nbsp;&nbsp; &nbsp; // substract holidays&nbsp; &nbsp; if (in_array($dt->format('Y-m-d'), $holidays)) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $return_data['holiday'][]=$dt->format('Y-m-d');&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; $return_data['working_days'][]=$dt->format('Y-m-d');&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp;}print_r($return_data['working_days']);&nbsp;?>
打开App,查看更多内容
随时随地看视频慕课网APP