首页 > 解决方案 > 在 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 变量)以秒表示。

标签: phplaravel

解决方案


@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


推荐阅读