Laravel – time difference

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.

Thank u for help

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

For storing this data:
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(IlluminateHttpRequest $request) 
{
    $flight = new Flight;
    $flight->unguard();
    $flight->create([
        //your other flight info
        'departure' = Carbon::parse($myTakeoffTimestamp),
        'arrival' => Carbon::parse($myArrivalTimestamp),
        'duration' => $takeoff->diffInHours($arrival)
    ]);
}

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x