Laravel-时差 [英] Laravel - time difference

查看:119
本文介绍了Laravel-时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欢迎光临!我有问题要问你.我正在为Laravel 5.2中的飞行日志编写代码.在公式化器中,我将具有起飞时间和到达时间,并且我不知道如何在laravel中计算时差并将其自动传递给数据库.因此,以最简单的方式,它将计算该时差,例如:takoeff-12 UTC到达-14UTC,然后将其作为飞行时数= 2保存到数据库中.

Welcome ! I have question to you. I'm coding for myself flight logbook in Laravel 5.2. In formular i'll have time of takeoff and time of arrival and i don't know how to do in laravel count of time difference and pass it automaticly to databas. So at easiest way it'll count this time difference for example: takoeff - 12 UTC arrival - 14UTC and then it'll save this time differece to database as Flight Hours = 2.

感谢您的帮助

推荐答案

Laravel附带了Carbon,它为此提供了一个简单的帮助器:

Laravel ships with Carbon which provides an easy helper for this:

$departure = Carbon::parse($myTakeoffTimestamp); // 12 UTC
$arrival = Carbon::parse($myArrivalTimestamp); // 14 UTC

$diff = $departure->diffInHours($arrival, false); // 2

用于存储此数据:

Schema::create('flights', function(Blueprint $table){
    //other table stuff...

    $table->timestamp('departure');
    $table->timestamp('arrival');
    $table->timestamp('duration');
});

然后,您可以在控制器中执行此操作:

Then you can just do this in your controller:

public function store(Illuminate\Http\Request $request) 
{
    $flight = new Flight;
    $flight->unguard();
    $flight->create([
        //your other flight info
        'departure' = Carbon::parse($myTakeoffTimestamp),
        'arrival' => Carbon::parse($myArrivalTimestamp),
        'duration' => $takeoff->diffInHours($arrival)
    ]);
}

由于Schema builder中的timestamp()定义在Carbon的默认格式(即时间戳记)下可以完美地工作,因此无需额外的工作即可通过此方法将其导入数据库.

As the timestamp() definition in your Schema builder works flawlessly with Carbon's default formatting (which is a timestamp), there is no extra work to get it into the database with this method.

这篇关于Laravel-时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆