欢迎!我有问题想问你。我正在 Laravel 5.2 中为自己编写飞行日志。在公式中,我将有起飞时间和到达时间,但我不知道如何在 laravel 中计算时间差并将其自动传递到数据库。因此,最简单的方法是计算此时间差,例如:takoeff - 12 UTC 到达 - 14UTC,然后将此时间差保存到数据库中,即飞行时间 = 2。
谢谢你的帮助
最佳答案
Laravel 附带了 Carbon
,它为此提供了一个简单的帮助器:
$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');
});
然后你可以在 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
的默认格式(即时间戳)完美配合,因此使用此方法无需额外工作即可将其存入数据库。
关于mysql - Laravel - 时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41249593/