簡體   English   中英

計算兩個日期之間的天數

[英]Count the days between two dates

我想做的是計算兩個日期之間的天數(周末除外),我已經完成了使用下面的函數的操作。 但是,每當$startDate大於$endDate我就無法獲得正確的結果。 我嘗試使用if ($startDate>$endDate)並且我有這種情況,實際上我不知道下一步是什么。

function getWorkingDays($startDate,$endDate){
        // do strtotime calculations just once
        $startDate = strtotime($startDate);
        $endDate = strtotime($endDate);

        //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
        //We add one to inlude both dates in the interval.
        $days = ($endDate - $startDate) / 86400 + 0;

        $no_full_weeks = floor($days / 7);
        $no_remaining_days = fmod($days, 7);

        //It will return 1 if it's Monday,.. ,7 for Sunday
        $the_first_day_of_week = date("N", $startDate);
        $the_last_day_of_week = date("N", $endDate);

        // If one of the value is empty it will return "0"
         if ($startDate == '' || $endDate == '')
                return "0"; // Default value

        //---->The two can be equal in leap years when february has 29 days, the equal sign is added here
        //In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
        if ($the_first_day_of_week <= $the_last_day_of_week) {
            if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
            if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
        }
        else {
            // (edit by Tokes to fix an edge case where the start day was a Sunday
            // and the end day was NOT a Saturday)

            // the day of the week for start is later than the day of the week for end
            if ($the_first_day_of_week == 7) {
                // if the start date is a Sunday, then we definitely subtract 1 day
                $no_remaining_days--;

                if ($the_last_day_of_week == 6) {
                    // if the end date is a Saturday, then we subtract another day
                    $no_remaining_days--;
                }
            }
            else {
                // the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
                // so we skip an entire weekend and subtract 2 days
                $no_remaining_days -= 2;
            }
        }

        //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
        //---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
        $workingDays = $no_full_weeks * 5;
        if ($no_remaining_days > 0 )
        {
          $workingDays += $no_remaining_days;
        }

        return $workingDays;
    }
$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");

$timeDiff = abs($endTimeStamp - $startTimeStamp);

$numberDays = $timeDiff/86400;  // 86400 seconds in one day

// and you might want to convert to integer
$numberDays = intval($numberDays);

要么

function dateDiff($start, $end) {
  $start_ts = strtotime($start);
  $end_ts = strtotime($end);
  $diff = $end_ts - $start_ts;
  return round($diff / 86400);
}
echo dateDiff("2011-02-15", "2012-01-16").'days';

//Get number of days deference between current date and given date.
echo dateDiff("2011-02-15", date('Y-m-d')).'days';  

對於Count天(不包括以下代碼)

$start = new DateTime('7/17/2017');
$end = new DateTime('7/24/2017');
$oneday = new DateInterval("P1D");
$daysName = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri');
$days = array();
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
    $day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
    if($day_num < 6) { /* weekday */

        $days[$day->format("Y-m-d")] = date('D', strtotime($day->format("Y-m-d")));;
    } 
} 
echo "<pre>";
print_r($days);   
echo count($days);

這將檢查開始日期是否小於結束日期。 如果是,那么它將顯示日期。

<?php

if($days = getWorkingDays("2017-05-01","2018-01-01")){
  echo $days;
}

function getWorkingDays($startDate,$endDate){
  $startDate = strtotime($startDate);
  $endDate = strtotime($endDate);

  if($startDate <= $endDate){
    $datediff = $endDate - $startDate;
    return floor($datediff / (60 * 60 * 24));
  }
  return false;
}
?>

輸出 :245

使用的功能:

  1. strtotime() :strtotime()函數將英語文本日期時間解析為Unix時間戳。
  2. floor() :floor()函數將數字向下舍入到最接近的整數

編輯1 :排除周末后的工作日(周六和周日)

//getWorkingDays(start_date, end_date)
if($days = getWorkingDays("2017-05-01","2018-01-01")){
      echo $days;
}

function getWorkingDays($startDate,$endDate){

  $days = false;
  $startDate = strtotime($startDate);
  $endDate = strtotime($endDate);

  if($startDate <= $endDate){
    $datediff = $endDate - $startDate;
    $days = floor($datediff / (60 * 60 * 24)); // Total Nos Of Days

    $sundays = intval($days / 7) + (date('N', $startDate) + $days % 7 >= 7); // Total Nos Of Sundays Between Start Date & End Date
    $saturdays = intval($days / 7) + (date('N', $startDate) + $days % 6 >= 6); // Total Nos Of Saturdays Between Start Date & End Date

    $days = $days - ($sundays + $saturdays); // Total Nos Of Days Excluding Weekends
  }
  return $days;
}
?>

資料來源:

  1. 計算兩個日期之間的星期天
  2. intval()函數用於獲取變量的整數值。
  3. 請參見描述date('N',$ date)N-一天的ISO-8601數字表示形式(星期一為1,星期日為7)

有用於執行此操作的代碼腳本。

<?php

  $now = time(); // or your date as well 
  $your_date = strtotime("2010-01-01");
  $datediff = $now - $your_date;

  echo floor($datediff / (60 * 60 * 24));
?>

要么

 $datetime1 = new DateTime("2010-06-20");

 $datetime2 = new DateTime("2011-06-22");

 $difference = $datetime1->diff($datetime2);

 echo 'Difference: '.$difference->y.' years, ' 
               .$difference->m.' months, ' 
               .$difference->d.' days';

 print_r($difference);

嘗試這個

public function datediff($sdate,$edate){

    $diffformat='%a';
    $date1              = date_create($sdate);
    $date2              = date_create($edate);
    $diff12             = date_diff($date2, $date1);
    $days               = $diff12->format($diffformat) + 1;}

使用date_diff()返回兩個DateTime對象之間的差。

$diff=date_diff($startDate,$endDate);

編輯:我在評論中注意到您要排除周末/天( 但是您沒有在帖子中提及! ),您可以添加要從一周中排除的天數

您可以使用DateTime :: diff並為絕對結果使用選項(始終為正差)

<?php
function daysBetween2Dates($date1, $date2, $execludedDaysFromWeek = 0)
{
    try{
        $datetime1 = new \DateTime($date1);
        $datetime2 = new \DateTime($date2);
    }catch (\Exception $e){
        return false;
    }
    $interval = $datetime1->diff($datetime2,true);
    $days = $interval->format('%a');
    if($execludedDaysFromWeek < 0 || $execludedDaysFromWeek > 7){
        $execludedDaysFromWeek = 0 ;
    }
    return ceil($days * (7-$execludedDaysFromWeek) / 7);
}

使用范例

// example 1 : without weekend days, start date is the first one
$days = daysBetween2Dates('2016-12-31','2017-12-31');
echo $days;
// example 2 : without weekend days, start date is the second one
$days = daysBetween2Dates('2017-12-31', '2016-12-31');
echo  "<br>\n" .$days;
// example 3 : with weekend days, it returns 6 days for the week
$days = daysBetween2Dates('2017-12-31', '2017-12-24',-1);
echo  "<br>\n" .$days;
exit;

這個輸出

365
365
6

現場演示( https://eval.in/835862

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM