0

In laravel suppose i have input like this '10:30:00' an i want to split them by ":" and covert them into integers and add them like here it will be 10+30=40 will be the output. i used 'explode' to split but i don't know how to add the values.if anyone can help please...thanks.here is my sample code where i am taking time as string.this is not duplicate question as i want to use the exploid function to be used and taking input from user as string. not as time. the question is showing as duplicate of my question is about time only. :)

$startTime= $request->input('starttime');
$finishTime=$request->input('endtime');
$stime = explode(':',$startTime);
$estime = explode(':',$finishTime);
TIGER
  • 2,864
  • 5
  • 35
  • 45
incorporeal
  • 177
  • 1
  • 4
  • 15
  • Why you want to add minutes and hours ? – TIGER Dec 20 '16 at 05:25
  • i want to know the way to add them..i will multiply the hour by 60 and add with minutes. i want the output in minutes. – incorporeal Dec 20 '16 at 05:27
  • For laravel I prefer to use Carbon as @kapil.dev answer you. It is not good practice to explode the time and add minutes and hours only. Secounds are also useful in some cases. – TIGER Dec 20 '16 at 05:50

4 Answers4

4

You can use Carbon to extract Hour and Minute

$startTime= \Carbon::parse($request->input('starttime'));
$stime = ($startTime->hour * 60) + $startTime->minute;
$finishTime=\Carbon::parse($request->input('endtime'));
$estime = ($finishTime->hour * 60) + $finishTime->minute;

To know more about Carbon refer : http://carbon.nesbot.com/docs/#api-interval

Rohit shah
  • 833
  • 4
  • 15
kapilpatwa93
  • 4,111
  • 2
  • 13
  • 22
2

you can use array_sum($array_name);

Before Performing array_sum You will have to do $stime[0]*60 and $etime[0]*60 so as to convert them into minutes

for $stime do $startsum = array_sum($stime);

and for $etime do $endsum =array_sum($etime);

Hope this Helps You.

itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29
Rohit shah
  • 833
  • 4
  • 15
1

Did you try like this....

<?php
$time='10:30:00';
$stime = explode(':',$time);


$sum=0;
foreach ($stime as $s)
{
    $sum=$sum+$s;
}
echo $sum;

?>

And if you to use array_sum()..try like this...

$sum=array_sum($stime);
echo $sum;
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
0

You can also use date_parse method for php.

<?php 
$startTime= '10:30:02';
$finishTime= '12:30:20';

$parsed = date_parse($startTime);
$startTimeSeconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

$parsed = date_parse($finishTime);
$finishTimeSeconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

?>
TIGER
  • 2,864
  • 5
  • 35
  • 45