Php 无周末的日差

Php 无周末的日差,php,codeigniter,date,Php,Codeigniter,Date,我想计算用户输入的总日差 例如,当用户输入 开始日期=2012-09-06和结束日期=2012-09-11 目前,我正在使用此代码查找差异 $count = abs(strtotime($start_date) - strtotime($end_date)); $day = $count+86400; $total = floor($day/(60*60*24)); 总计结果为6。但问题是,我不想包括周末(周六和周日) 所以结果是4 ----更新--- 我有一个包含日期的表,表名是holi

我想计算用户输入的总日差

例如,当用户输入

开始日期=2012-09-06
结束日期=2012-09-11

目前,我正在使用此代码查找差异

$count = abs(strtotime($start_date) - strtotime($end_date));
$day   = $count+86400;
$total = floor($day/(60*60*24));
总计结果为6。但问题是,我不想包括周末(周六和周日)

所以结果是4

----更新---

我有一个包含日期的表,表名是holiday date

例如,该表包含
2012-09-07

因此,总天数将为3天,因为它没有计算假期日期


如何使输入的日期与表中的日期相等?

使用
DateTime

$datetime1 = new DateTime('2012-09-06');
$datetime2 = new DateTime('2012-09-11');
$interval = $datetime1->diff($datetime2);
$woweekends = 0;
for($i=0; $i<=$interval->d; $i++){
    $datetime1->modify('+1 day');
    $weekday = $datetime1->format('w');

    if($weekday !== "0" && $weekday !== "6"){ // 0 for Sunday and 6 for Saturday
        $woweekends++;  
    }

}

echo $woweekends." days without weekend";

// 4 days without weekends
$datetime1=新日期时间('2012-09-06');
$datetime2=新日期时间('2012-09-11');
$interval=$datetime1->diff($datetime2);
$WO=0;
对于($i=0;$id;$i++){
$datetime1->修改(“+1天”);
$weekday=$datetime1->格式('w');
如果($weekday!=“0”&&&$weekday!=“6”){//0表示周日,6表示周六
$WO++;
}
}
echo$woweekends.“没有周末的日子”;
//4天没有周末
看看这篇文章:

(在您的情况下,您可以省略“假期”部分,因为您只在工作日/工作日之后)


我最喜欢的东西非常简单:,和

日期('N')获取一周中的某一天(1-周一,7-周日)

$start=strotime('2012-08-06');
$end=strottime('2012-09-06');
$count=0;
while(日期('Y-m-d',$start)
这里有一个替代方法来计算两个日期之间的工作日,也不包括使用Pear的Date\u假日的美国假日

$start_date和$end_date应该是DateTime对象(您可以使用
newdatetime('@.$timestamp)
将时间戳转换为DateTime对象)


在我的例子中,我需要与OP相同的答案,但想要更小的@Bojan的回答是有效的,但我不喜欢它不适用于
DateTime
对象,需要使用时间戳,并且与
字符串进行比较,而不是实际对象本身(感觉很粗糙)。。。这是他的答案的修订版

function getWeekdayDifference(\DateTime $startDate, \DateTime $endDate)
{
    $days = 0;

    while($startDate->diff($endDate)->days > 0) {
        $days += $startDate->format('N') < 6 ? 1 : 0;
        $startDate = $startDate->add(new \DateInterval("P1D"));
    }

    return $days;
}
函数getWeekdayDifference(\DateTime$startDate、\DateTime$endDate) { $days=0; while($startDate->diff($endDate)->days>0){ $days+=$startDate->format('N')<6-1:0; $startDate=$startDate->add(新建\日期间隔(“P1D”); } 返回$days; }
根据@xzdead的评论,如果您希望包括开始和结束日期:

function getWeekdayDifference(\DateTime $startDate, \DateTime $endDate)
{
    $isWeekday = function (\DateTime $date) {
        return $date->format('N') < 6;
    };

    $days = $isWeekday($endDate) ? 1 : 0;

    while($startDate->diff($endDate)->days > 0) {
        $days += $isWeekday($startDate) ? 1 : 0;
        $startDate = $startDate->add(new \DateInterval("P1D"));
    }

    return $days;
}
函数getWeekdayDifference(\DateTime$startDate、\DateTime$endDate) { $isWeekday=函数(\DateTime$date){ 返回$date->format('N')<6; }; $days=$isWeekday($endDate)?1:0; while($startDate->diff($endDate)->days>0){ $days+=$isWeekday($startDate)?1:0; $startDate=$startDate->add(新建\日期间隔(“P1D”); } 返回$days; }
如果您不需要完整的天数,但需要精确的秒数,请尝试此代码。这将接受unix时间戳作为输入

function timeDifferenceWithoutWeekends($from, $to) {
    $start = new DateTime("@".$from);
    $current = clone $start;
    $end = new DateTime("@".$to);
    $sum = 0;
    while ($current<$end) {
        $endSlice = clone $current;
        $endSlice->setTime(0,0,0);
        $endSlice->modify('+1 day');
        if ($endSlice>$end) {
            $endSlice= clone $end;
        }
        $seconds = $endSlice->getTimestamp()-$current->getTimestamp();
        $currentDay = $current->format("D");
        if ($currentDay != 'Sat' && $currentDay != 'Sun') {
            $sum+=$seconds;
        }
        $current = $endSlice;
    }
    return $sum;
}
无周函数时差($from,$to){
$start=新日期时间(“@”$from);
$current=克隆$start;
$end=新的日期时间(“@”。$to);
$sum=0;
而($currentsetTime(0,0,0);
$endSlice->modify(“+1天”);
如果($endSlice>$end){
$endSlice=clone$end;
}
$seconds=$endSlice->getTimestamp()-$current->getTimestamp();
$currentDay=$current->format(“D”);
如果($currentDay!='Sat'&&$currentDay!='Sun'){
$sum+=$seconds;
}
$current=$endSlice;
}
返回$sum;
}

在没有周末的情况下,最简单、最快的方法就是使用图书馆

下面是一个如何使用它的示例:

<?php

$from = Carbon\Carbon::parse('2016-05-21 22:00:00');
$to = Carbon\Carbon::parse('2016-05-21 22:00:00');
echo $to->diffInWeekdays($from);

请看一看这个精确的php函数,它返回不包括周末的天数计数

function Count_Days_Without_Weekends($start, $end){
    $days_diff = floor(((abs(strtotime($end) - strtotime($start))) / (60*60*24)));
    $run_days=0;
    for($i=0; $i<=$days_diff; $i++){
        $newdays = $i-$days_diff;
        $futuredate = strtotime("$newdays days");
        $mydate = date("F d, Y", $futuredate);
        $today = date("D", strtotime($mydate));             
        if(($today != "Sat") && ($today != "Sun")){
            $run_days++;
        }
    }
return $run_days;
}
function Count\u Days\u无周末($start,$end){
$days_diff=floor((abs(strotime($end)-strotime($start))/(60*60*24));
$run_days=0;

对于($i=0;$i一种使用碳的非常简单的解决方案

以下是从控制器存储函数调用的存储库文件

<?php

namespace App\Repositories\Leave;

use App\Models\Holiday;
use App\Models\LeaveApplication;
use App\Repositories\BaseRepository;
use Carbon\Carbon;

class LeaveApplicationRepository extends BaseRepository
{
    protected $holiday;

    public function __construct(LeaveApplication $model, Holiday $holiday)
    {
        parent::__construct($model);
        $this->holiday = $holiday;
    }

    /**
     * Get all authenticated user leave
     */
    public function getUserLeave($id)
    {
        return $this->model->where('employee_id',$id)->with(['leave_type','approver'])->get();
    }

    /**
     * @param array $request
     */
    public function create($request)
    {
        $request['total_days'] = $this->getTotalDays($request['start_date'],$request['end_date']);

        return $this->model->create($request->only('send_to','leave_type_id','start_date','end_date','desc','total_days'));
    }

    /**
     * Get total leave days
     */
    private function getTotalDays($startDate, $endDate)
    {
        $holidays = $this->getHolidays(); //Get all public holidays
        $leaveDays = 0; //Declare values which hold leave days
        //Format the dates
        $startDate = Carbon::createFromFormat('Y-m-d',$startDate);
        $endEnd = Carbon::createFromFormat('Y-m-d',$endDate);
        //Check user dates
        for($date = $startDate; $date <= $endEnd; $date->modify('+1 day')) {
            if (!$date->isWeekend() && !in_array($date,$holidays)) {
                $leaveDays++; //Increment days if not weekend and public holidays
            }
        }
        return $leaveDays; //return total days
    }

    /**
     * Get Current Year Public Holidays
     */
    private function getHolidays()
    {
        $holidays = array();
        $dates = $this->holiday->select('date')->where('active',1)->get();
        foreach ($dates as $date) {
            $holidays[]=Carbon::createFromFormat('Y-m-d',$date->date);
        }
        return $holidays;
    }
}

以下是@dan lee函数的改进版本:

function get_total_days($start, $end, $holidays = [], $weekends = ['Sat', 'Sun']){

    $start = new \DateTime($start);
    $end   = new \DateTime($end);
    $end->modify('+1 day');

    $total_days = $end->diff($start)->days;
    $period = new \DatePeriod($start, new \DateInterval('P1D'), $end);

    foreach($period as $dt) {
        if (in_array($dt->format('D'),  $weekends) || in_array($dt->format('Y-m-d'), $holidays)){
            $total_days--;
        }
    }
    return $total_days;
}
要使用它:

$start    = '2021-06-12';
$end      = '2021-06-17';
$holidays = ['2021-06-15'];
echo get_total_days($start, $end, $holidays); // Result: 3

我不能使用diff和DatePeriod…因为php版本5.2…我有办法更改diff…但我不知道如何更改DatePeriod…你能帮我吗?@Belajar你可以通过每次迭代添加一天来模仿这种行为。请参阅此论坛帖子以供参考:我相信在这段代码中,如果假日是周六或周日,那么它将被扣除两次。应该有一个“elseif”。我从最终计数中再减去一天。我测试了它,说到今天为止有多少个工作日(2016年9月1日)结果我得到了1。没有!所以我可以多休息一天计算。谢谢@dan lee的帮助。它像魔术一样工作。我所做的只是复制并粘贴到我的代码中,它工作了!!!没有完全工作。试试这些日期:$start=strotime('2015-12-01');$end=strotime('2015-12-15'));结果是10天,但必须是11天。为什么,范围内的第一个星期一(2015-12-07)没有按正确的方式计算。可能是一个错误?因此,任何寻找此“现在碳API”的人都有此功能,它应该是
$interval->Days
而不是
$interval->d
<?php

$from = Carbon\Carbon::parse('2016-05-21 22:00:00');
$to = Carbon\Carbon::parse('2016-05-21 22:00:00');
echo $to->diffInWeekdays($from);
/**
 * Getting the Weekdays count[ Excludes : Weekends]
 * 
 * @param type $fromDateTimestamp
 * @param type $toDateTimestamp
 * @return int
 */
public static function getWeekDaysCount($fromDateTimestamp = null, $toDateTimestamp=null) {

    $startDateString   = date('Y-m-d', $fromDateTimestamp);
    $timestampTomorrow = strtotime('+1 day', $toDateTimestamp);
    $endDateString     = date("Y-m-d", $timestampTomorrow);
    $objStartDate      = new \DateTime($startDateString);    //intialize start date
    $objEndDate        = new \DateTime($endDateString);    //initialize end date
    $interval          = new \DateInterval('P1D');    // set the interval as 1 day
    $dateRange         = new \DatePeriod($objStartDate, $interval, $objEndDate);

    $count = 0;

    foreach ($dateRange as $eachDate) {
        if (    $eachDate->format("w") != 6 
            &&  $eachDate->format("w") != 0 
        ) {
            ++$count;
        }
    }
    return $count;
}
function Count_Days_Without_Weekends($start, $end){
    $days_diff = floor(((abs(strtotime($end) - strtotime($start))) / (60*60*24)));
    $run_days=0;
    for($i=0; $i<=$days_diff; $i++){
        $newdays = $i-$days_diff;
        $futuredate = strtotime("$newdays days");
        $mydate = date("F d, Y", $futuredate);
        $today = date("D", strtotime($mydate));             
        if(($today != "Sat") && ($today != "Sun")){
            $run_days++;
        }
    }
return $run_days;
}
<?php

namespace App\Repositories\Leave;

use App\Models\Holiday;
use App\Models\LeaveApplication;
use App\Repositories\BaseRepository;
use Carbon\Carbon;

class LeaveApplicationRepository extends BaseRepository
{
    protected $holiday;

    public function __construct(LeaveApplication $model, Holiday $holiday)
    {
        parent::__construct($model);
        $this->holiday = $holiday;
    }

    /**
     * Get all authenticated user leave
     */
    public function getUserLeave($id)
    {
        return $this->model->where('employee_id',$id)->with(['leave_type','approver'])->get();
    }

    /**
     * @param array $request
     */
    public function create($request)
    {
        $request['total_days'] = $this->getTotalDays($request['start_date'],$request['end_date']);

        return $this->model->create($request->only('send_to','leave_type_id','start_date','end_date','desc','total_days'));
    }

    /**
     * Get total leave days
     */
    private function getTotalDays($startDate, $endDate)
    {
        $holidays = $this->getHolidays(); //Get all public holidays
        $leaveDays = 0; //Declare values which hold leave days
        //Format the dates
        $startDate = Carbon::createFromFormat('Y-m-d',$startDate);
        $endEnd = Carbon::createFromFormat('Y-m-d',$endDate);
        //Check user dates
        for($date = $startDate; $date <= $endEnd; $date->modify('+1 day')) {
            if (!$date->isWeekend() && !in_array($date,$holidays)) {
                $leaveDays++; //Increment days if not weekend and public holidays
            }
        }
        return $leaveDays; //return total days
    }

    /**
     * Get Current Year Public Holidays
     */
    private function getHolidays()
    {
        $holidays = array();
        $dates = $this->holiday->select('date')->where('active',1)->get();
        foreach ($dates as $date) {
            $holidays[]=Carbon::createFromFormat('Y-m-d',$date->date);
        }
        return $holidays;
    }
}
<?php

namespace App\Http\Controllers\Leave;

use App\Http\Controllers\AuthController;
use App\Http\Requests\Leave\LeaveApplicationRequest;
use App\Repositories\Leave\LeaveApplicationRepository;
use Exception;

class LeaveApplicationController extends AuthController
{
    protected $leaveApplication;

    /**
     * LeaveApplicationsController constructor.
     */
    public function __construct(LeaveApplicationRepository $leaveApplication)
    {
        parent::__construct();
        $this->leaveApplication = $leaveApplication;
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(LeaveApplicationRequest $request)
    {
        try {
            $this->leaveApplication->create($request);
            return $this->successRoute('leaveApplications.index','Leave Applied');
        }
        catch (Exception $e) {
            return $this->errorWithInput($request);
        }
    }
}
  
function get_total_days($start, $end, $holidays = [], $weekends = ['Sat', 'Sun']){

    $start = new \DateTime($start);
    $end   = new \DateTime($end);
    $end->modify('+1 day');

    $total_days = $end->diff($start)->days;
    $period = new \DatePeriod($start, new \DateInterval('P1D'), $end);

    foreach($period as $dt) {
        if (in_array($dt->format('D'),  $weekends) || in_array($dt->format('Y-m-d'), $holidays)){
            $total_days--;
        }
    }
    return $total_days;
}
$start    = '2021-06-12';
$end      = '2021-06-17';
$holidays = ['2021-06-15'];
echo get_total_days($start, $end, $holidays); // Result: 3