php - 在 Laravel 中计算时差
问题描述
我是初学者网络开发人员。
我在 Laravel 5.8 中制作我的网站。
这是我的模型和迁移:
class Timecycle extends Model
{
protected $fillable = [
'case_id',
'timecycleable_id',
'timecycleable_type',
'status',
'worked_time'
];
protected $casts = [
'id' => 'int',
'case_id' => 'int',
];
protected $dates = [
'created_at',
'updated_at'
];
public function stopwatch()
{
return $this->morphTo();
}
Schema::create('timecycles', function (Blueprint $table) {
$table->increments('id');
$table->integer('timecycleable_id');
$table->string('timecycleable_type');
$table->integer('case_id')->unsigned();
$table->foreign('case_id')->references('id')->on('case_instances')->onDelete('cascade');
$table->boolean('status')->default(0);
$table->integer('worked_time')->default(0);
$table->timestamps();
});
控制器:
public function sync()
{
$activeStopwatches = $this->getActiveStopwatches();
foreach ($activeStopwatches as $activeStopwatch) {
foreach ($activeStopwatch->timeCycle as $timeCycle) {
$newTime = now() - $timeCycle->updated_at;
$timeCycle->update(['worked_time' => $timeCycle->worked_time + $newTime]);
}
}
}
public function getActiveStopwatches()
{
return $this->stopwatch::with(['timeCycle' => function ($q) {
$q->where('status', 1);
}, 'caseInstance'])
->where('user_id', Auth()->user()->id)
->whereHas('timeCycle', function ($q) {
$q->where('status', 1);
})
->get();
}
我有一个显示当前秒表的方法:getActiveStopwatches。工作正常。在 sync() 函数中,我想更新工作时间。所以:当前时间 - 上次更新日期,将结果保存到工作时间。
这个计算条目是否正确?我要保存的时间($ newTime 变量)以秒表示。
解决方案
@trzew我希望打击代码对您有所帮助。
使用碳\碳;
$newTime = now() - $timeCycle->updated_at;
is not working fine , use time difference function to calculate difference
$mytime = Carbon\Carbon::now();
$totalDuration = $newTime->diffInSeconds($timeCycle->updated_at);
gmdate('H:i:s', $totalDuration);
// 00:00:21
推荐阅读
- r - 构建 r 包
- python - python3 additional problem with nested default dict
- python - 从文本文件导入数据时如何在 Python 字典中增加值?
- html5-video - 当我们使用 src 作为 YouTube 视频根 URL 时,有什么方法可以为 HTML 视频标签设置文件名
- julia - 如何设置 Plots 的默认属性?
- python - Django用户模型两次保存到数据库中
- c - 如何安全实现File Tree Walk(C语言)
- python - 将 print 的输出写入 python 中的文件
- wpf - 没有蓝牙控制面板的ble配对
- c# - 检查坐标是否位于多边形内c#