I have two times $first = 16 (seconds or minutes)
& $second = 10 (seconds or minutes)
What i want to achieve - I want to add this two times like $result = $first $second
& the result is in seconds & minutes formet
like
$first = 16 seconds;
$second = 2 minutes;
$result = $first $second; // 2 minutes, 16 seconds
so, how can we do this in code
I have this refrence code to get the time interval of two times
$in1 = explode(' ', "clock in time = 20 minutes");
$out1 = explode(' ', "clock out time = 10 minutes");
$start_time1 = $in1[4] . ' ' . $in1[5];
$end_time1 = $out1[4] . ' ' . $out1[5];
$start1 = Carbon::parse($start_time1);
$end1 = Carbon::parse($end_time1);
$dd1 = $end1->diffForHumans($start1, [
'parts' => 2,
'join' => ', ',
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
]);
CodePudding user response:
Carbon intervals allow you to create an interval instance from strings like 20 minutes
or 10 seconds
so you can leverage that with some date operations to get what you need:
$in1 = explode('=', "clock in time = 20 minutes");
$out1 = explode('=', "clock out time = 10 minutes");
$startinterval = CarbonInterval::fromString(trim($in1[1]));
$endinterval = CarbonInterval::fromString(trim($out1[1]));
$now = CarbonImmutable::now();
$interval = $now->add($startinterval)->add($endinterval)->diffAsCarbonInterval($now);
CodePudding user response:
You can convert your times in seconds, do the addition, then convert to time again.
$start = $in1[5] === 'seconds' ? $int1[4] : $int1[4] * 60;
$end = $out1[5] === 'seconds' ? $out1[4] : $out1[4] * 60;
$totalInSeconds = (int) $start (int) $end;
$dd1 = gmdate('i', $totalInSeconds) .' minutes, '. gmdate('s', $totalInSeconds) .' seconds';
echo $dd1;