Laravel 7:计算有条件的两个日期之间的天数

问题描述 投票:0回答:3

我陷入了复杂的计算中。我想计算两天之间的天数。但它需要检查其他两个表中的

date
列,在两个日期之间
date
是否存在。其概念是:用户提交休假申请时需要选择开始和结束日期。两天之间的天数将保存在 leaves 表中。但在保存之前需要检查两个日期之间是否有假期或每周假期。如果假期或每周假期匹配,则将从总天数中扣除假期总数。

每周假期:(型号名称:WorkingDay)

id 工作状态
1 周五 1

假期表:(型号名称:假期)

id 日期 出版物状态
1 2022-05-26 1

离开餐桌:

id 开始日期 结束日期 总天数
1 2022-05-25 2022-05-28 2

控制器:

   $leave = new Leave;
   $leave->start_date = $request->start_date;
   $leave->end_date = $request->end_date;

   $start_day = date("D", strtotime($request->start_date));
   $end_day = date("D", strtotime($request->end_date));

   $start = Carbon::parse($request->start_date);
   $end = Carbon::parse($request->end_date);
   $total_days = $end->diffInDays($start);

   
   $weekly_holidays = WorkingDay::where('working_status', 0)
   ->get(['day']);

   $monthly_holidays= Holiday::where('publication_status', 1)->get(['date']);
    $total_days = //need solution here

   if($request->halfday == 1){
        $leave->total_days = 0.5;
    }
    else{
        $leave->total_days = $total_days;
    }

示例:

 WorkingDay = day = Fri
 Holiday = date = 2022-05-26
 start_date = 2022-05-25
 end_date = 2022-05-28
 total_days = 2 
 // from 25 to 28, total days is 4, but 26 is a holiday, and 27 is friday. Holiday can be multiple dates. If there is multiple holidays between start and end date, it will calculate according to this. 

我不确定如何编写代码来验证这些条件。请帮助我。

php laravel conditional-statements laravel-7
3个回答
1
投票

我已尝试准确检查您想要的内容,并为您做出了这个答案。希望这就是您想要解释的内容

表:工作日

控制器:

public function insertLeaves(Request $request) {

    $leave = new Leave;
    $leave->start_date = $request->start_date;
    $leave->end_date = $request->end_date;

    $start_day = date("D", strtotime($request->start_date));
    $end_day = date("D", strtotime($request->end_date));

    $start = Carbon::parse($request->start_date);
    $end = Carbon::parse($request->end_date);
    $total_days = $end->diffInDays($start);

    // Gets the working days in comma seperated without the key from the database [Example: Sat, Sun, Mon, Tue, Wed, Thu] in array
    $working_days = WorkingDay::where('working_status', 0)
    ->get(['day'])->map(function($day) {
        return $day->day;
    })->toArray();

    // Gets the holidays in comma seperated dates without the key from the database [Example: 2022-05-26, 2022-05-28] in array
    $holidays= Holiday::where('publication_status', 1)->get(['date'])->map(function($date) {
        return date('Y-m-d', strtotime($date->date));
    })->toArray();

    // Get the weekend holidays we get between the start date and end date by the helper function we created 
    $weekend_holidays = $this->sumHolidays($working_days, $request->start_date , $total_days, 'weekends');

    // Get the holidays if have any between the start date and end date by the helper function we created 
    $monthly_holidays = $this->sumHolidays($holidays, $request->start_date , $total_days, 'holidays');
    
    $total_leaves = $total_days - $weekend_holidays - $monthly_holidays + 1; //need solution here;

    if($request->halfday == 1){
        $leave->total_days = 0.5;
    }
    else{
        $leave->total_days = $total_leaves;
    }
    $leave->save();

}

function sumHolidays($days, $start_date, $diff, $type) {
    $total_days = 0;
    $i = 0;
    while ($i <= $diff) {
        $tsDate = strtotime($start_date . ' ' .'+ '.$i.' days');
        if($type == 'weekends') {
            $day = date('D', $tsDate);
            if(!in_array($day, $days)) {
                $total_days++;
            }
        } elseif($type == 'holidays') {
            $date = date('Y-m-d', $tsDate);
            if(in_array($date, $days)) {
                $total_days++;
            }
        }
        $i++;
    }
    return $total_days;
}

输出示例:

Start Date = 2022-05-26
End Date = 2022-05-28
Working Days = day = ["Sat","Sun","Mon","Tue","Wed","Thu"]
Holidays = date = ["2022-05-26","2022-05-29"]
Weekend Holidays = 1
Monthly Holidays = 1
Total Days = 4
Total Leaves = 2 //As there is 1 Friday and 1 Holiday at 2022-05-26

0
投票

看看这个

public function store(Request $request) {
    
    
    $sdates = date("D", strtotime($request->start_date));
    $edates = date("D", strtotime($request->end_date));
    
    $leave_application = $this->validate($request, [
        'leave_category_id' => 'required',
        'start_date' => 'required',
        'end_date' => 'required',
    ]);
    // find the number of days between two dates
    $start_date = Carbon::parse(request('start_date'));
    $end_date = Carbon::parse(request('end_date'));

    $days = $start_date->diffInWeekdays($end_date);

    $weekly_holidays = WorkingDay::where('working_status', 0)
        ->get(['day'])
        ->toArray();

        if($weekly_holidays != null){

            foreach ($weekly_holidays as $weekly_holiday) {
                if ($sdates == $weekly_holiday['day'] || $edates == $weekly_holiday['day']) {
                    return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
                }               
               }                
        }

        $monthly_holidays = Holiday::where('holiday_date', '=', $request->start_date)
        ->first(['holiday_date']);
        
        
   if($monthly_holidays == null){
    
    $result = Leave::create($leave_application +['num_days' => $days] +['reason' =>request('reason')] + ['created_by' => auth()->user()->id]);
    
  
    $rds = LeaveBalance::where('leave_category_id',$request->leave_category_id)->where('created_by',$userId = Auth::user()->id)->first();
    
    if(!isset($rds)){

    $carbon = Carbon::now();
    $nowInTarawa = Carbon::now('Pacific/Tarawa');
    $year = $nowInTarawa->format('Y');
    $yearIntvalue = intval($year);

    $leave_balance = new LeaveBalance();
    $leave_balance->leave_category_id = $request->leave_category_id;
    $leave_balance->created_by = $userId = Auth::user()->id;
    $leave_balance->year = $yearIntvalue;
    $leave_balance->total_leave_taken = $leaves = Leave::getNumOfLeaveTaken($request->leave_category_id);
    $leave_balance->save();

}else

    {
        $leaves = Leave::getNumOfLeaveTaken($request->leave_category_id);
        LeaveBalance::where('created_by', $userId)->where('leave_category_id',$request->leave_category_id)
        ->update(['total_leave_taken' => $leaves]);

    }

    $leaveEntitlement = LeaveBalance::getNumOfLeaveEntitlment();

    $total_leave_balance = (int)$leaveEntitlement - (int)$leaves;
    // dd($leaveEntitlement);

    //  LeaveEntitlement::where('user_id', $userId)
    // ->update(['leave_entitlement' => $total_leave_balance]);
    
    LeaveBalance::where('created_by', $userId)
    ->update(['total_leave_balance' => $total_leave_balance]);

    $inserted_id = $result->id;

    if (!empty($inserted_id)) {
        return redirect()->route('leave.index')->with('message', 'Add successfully.');
    }
    return redirect()->route('leave.index')->with('exception', 'Operation failed !');

   }
   
   if($monthly_holidays != null){
                return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
    }
        
}

休假余额模型

    <?php

     namespace App\Models;

     use Illuminate\Database\Eloquent\Factories\HasFactory;
     use Illuminate\Database\Eloquent\Model;
     use App\Models\LeaveEntitlement;
     use DB;

     class LeaveBalance extends Model
     {
         use HasFactory;

    protected $table = 'leave_balances';

 
    protected $fillable = [

                    'created_by', 
                    'leave_category_id',
                    'total_leave_taken',
                    'year',
                   
                ];

   
    public function leaveEntitlement()
    {
        return $this->hasMany(leaveEntitlement::class);
    }

    public static function getNumOfLeaveEntitlment(){
                
       
        $leaveEntitlement  = DB::table('salary_level_user')
        ->where('user_id', \Auth::user()->id)->value('leave_entitlement');
       

        return $leaveEntitlement;
    }

}

休假权利模型

 <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
// use App\Models\LeaveEntitlement;

class LeaveEntitlement extends Model
{
    use HasFactory;

    protected $table = 'salary_level_user';

 
    protected $fillable = [

                    // 'created_by', 
                    'salary_level_id',
                    'user_id',
                    'leave_entitlement',
                   
                ];

   
    public function leaveEntitlement()
    {
        return $this->hasMany(leaveEntitlement::class);
    }

    

}


      

0
投票

您必须计算工作日、假期和休假天数。

试试这个代码

// I assume you are getting start_date and end_date in $request.
   $request->start_date = '2022-05-25';
   $request->end_date = '2022-05-28';

   $leave = new User;
   $leave->start_date = $request->start_date;
   $leave->end_date = $request->end_date;

   $start_day = date("D", strtotime($request->start_date));
   $end_day = date("D", strtotime($request->end_date));

   // this is change
   $start = strtotime($request->start_date);
   $end = strtotime($request->end_date);
   $diff = $end - $start;
   // This will calculate days between two days including start date and end date
   $diff_in_days = floor($diff/(60*60*24)) + 1;
   // assuming Fri is holiday and get count of it
   $weekly_holidays = WorkingDay::where('working_status', 1)
   ->get(['day'])->count();
   // Get count of monthly holidays
   $monthly_holidays= Holiday::where('publication_status', 1)->get(['date'])->count();
   // your result will be 4
   $total_days = $diff_in_days - $weekly_holidays - $monthly_holidays;
   

   if($request->halfday == 1){
        $leave->total_days = 0.5;
    }
    else{
        $leave->total_days = $total_days;
    }
© www.soinside.com 2019 - 2024. All rights reserved.