Reputation: 25
I have to implement some functionality using time calculation and my app has following type of code.
date_default_timezone_set(auth()->user()->timezone);
$t_now = \Carbon\Carbon::parse(date('Y-m-d H:i:s'));
$t_allowed = \Carbon\Carbon::parse($shift_details->start_time) ;
@endphp
@php
$check = $t_allowed->diffForHumans($t_now);
$search = 'after';
$dff_min = $t_allowed->diffInSeconds($t_now, true);
$init = $dff_min;
$day = floor($init / 86400);
$hours = floor(($init - $day * 86400) / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;
$late_not_late = $hours . ' hours ' . $minutes . ' minutes ' . $seconds . ' seconds ';
first i want to confirm that $dff_min = $t_allowed->diffInSeconds($t_now, true);
is returning minutes or seconds? Acording to my knowledge $dff_min
contain seconds
i know that hours could be calculate using (init /3600)
but what is the meaning of following statement
$hours = floor(($init - $day * 86400) / 3600);
why developer subtracting $day * 86400
from $init
?
similary we also can calculate seconds by $init/60 since in one minute there are 60 seconds but what is meaning of following line
$minutes = floor(($init / 60) % 60);
and also why he is using Modulo here
$seconds = $init % 60;
Upvotes: 0
Views: 1264
Reputation: 5056
\Carbon\Carbon::parse(date('Y-m-d H:i:s'))
will call twice the timelib and will loose the microseconds, just do \Carbon\Carbon::now()
and you don't need to reinvent the wheel, you can get this exact string with:
$t_now = \Carbon\Carbon::now();
$t_allowed = \Carbon\Carbon::parse($shift_details->start_time);
$late_not_late = $t_allowed->diffForHumans($t_now, ['parts' => 3, 'syntax' => CarbonInterface::DIFF_ABSOLUTE]);
$late_not_late will contain 2 days 9 hours 20 minutes
Upvotes: 3