Laravel 7: 如何计算两个时间格式值之间的差异并存储在数据库中?

Laravel 7: How to calculate difference between two time format value and store in database?

我想根据 check_in 时间和 opening_time 之间的差异计算延迟进入 table 并将时间值存储在出勤 table 中。 Time formate : 10:15:00。 check_in 和 check_out 时间将来自请求。

Example: 
open = 10:15:00
end = 18:00:00
check_in = 10:18:00
check_out = 17:50:00
late = open - check_in = 00:03:00
early = end - check_out = 00:10::

请看下面代码

设置Table

id opening_time ending_time
1 10:15:00 18:00:00

出勤率table

id late early
1 00:20:00 00:05:00

控制器:

public function AttendanceCSVStore(Request $request)
{
    $settings = Setting::where('id', 1)->get();
    $open = time($settings->opening_time);
    $end = time($settings->ending_time);

    for ($x = 1; $x <= $request->number; $x++) {
        $attendances = new Attendance;
        $attendances->check_in = $request->$x[4];
        $attendances->check_out = $request->$x[5];
        $csv_check_in = time($request->$x[4]);
        $csv_check_out = time($request->$x[5]);
        if( $csv_check_in > $open){
            $late_count =  $csv_check_in - $open;
            $attendances->late =  $late_count;
        }
        if( $csv_check_out < $end){
            $early_count = $csv_check_out - $end;
            $attendances->early = $early_count;
        }
        $attendances->save();
    }
    return redirect()->route('admin.attendance.manage')->with('message', 'Imported Successfully!');
}

这显示错误 Property [opening_time] does not exist on this collection instance. 而且这也不会计算并在迟到早列中插入时间。

你能帮我解决这个问题吗?

您得到的是一个集合,而不是单个记录。

如果你需要单条记录而不是集合,可以通过这种方式获取

$id = 1;
$settings = Setting::find($id);

echo $settings->opening_time;

$id = 1;
$settings = Setting::where('id', $id)->firstOrFail();

echo $settings->opening_time;

如果你需要一个集合并对其进行迭代,你可以这样做(但我认为这不是你所追求的)

$settings = Setting::where('id', 1)->get();

foreach ($settings as $setting) {
    echo $setting->opening_time;
}

更新

时差示例

public function index()
{
    $startTime = Carbon::parse('2020-02-11 04:04:26');
    $endTime = Carbon::parse('2020-02-11 04:36:56');

    $totalDuration =  $startTime->diff($endTime)->format('%H:%I:%S');
    dd($totalDuration);
}

输出:“00:32:30”

我认为这就是您想要的格式