i am fetching a data from my database according to client id. client id work time is different like:
00:15:00
00:20:00
etc.
this is not an array
i make this as dynamic array
$time[] = $alltime;
result showing this:
Array
(
[0] => 00:20:00
[1] => 00:15:00
[2] => 00:20:00
[3] => 00:20:00
[4] => 00:55:00
[5] => 00:05:00
)
i want to sum all time.
i tried many times and many way but output not showing according to time.
please help
Here's one way to get the sum, using strtotime to convert the times to seconds. Note that since strtotime produces a timestamp relative to the Unix Epoch, you need to subtract the start of the day (strtotime('00:00')) from each value to get the number of seconds in the time:
$time = array
(
'00:20:00',
'00:15:00',
'00:20:00',
'00:20:00',
'00:55:00',
'00:05:00'
);
$time_in_secs = array_map(function ($v) { return strtotime($v) - strtotime('00:00'); }, $time);
$total_time = array_sum($time_in_secs);
$hours = floor($total_time / 3600);
$minutes = floor(($total_time % 3600) / 60);
$seconds = $total_time % 60;
echo "Total time is "
. str_pad($hours, 2, '0', STR_PAD_LEFT)
. ":" . str_pad($minutes, 2, '0', STR_PAD_LEFT)
. ":" . str_pad($seconds, 2, '0', STR_PAD_LEFT) . "\n";
Output:
Total time is 02:15:00
Demo on 3v4l.org
You could also simplify the code by using array_reduce to compute $total_time instead of array_map and array_sum:
$total_time = array_reduce($time, function ($c, $v) { return $c + strtotime($v) - strtotime('00:00'); }, 0);
Alternate demo
Related
I think Time object is just a mess. I really never learn how they works.
I have an array with data: 09:00-09:20 and 12:30-13:00.
Now i like to calculate the time between 09:00-09:20.
So i break up the array:
$break_1_dur = $usr_breaks['skift_rast1'];
//returns: 09:00-09:20
I break up the string:
$break_1_start = substr($break_1_dur,0,5);
//returns: 09:00
$break_1_ends = substr($break_1_dur,6,5);
//returns: 09:20
And now i'll use DateTime diff to calculate the time:
$break_1_dur = $break_1_start->diff($break_1_ends);
I have tried to make strings to "DateTime" with:
$break_1_start = new DateTime();
How can i in a easy way calculate this?
This should work for you:
Here I first split your array into the following structure with array_map():
Array
(
[skift_rast1] => Array
(
[start] => 09:00
[end] => 09:20
)
[skift_rast2] => Array
(
[start] => 12:30
[end] => 13:00
)
)
The I loop through all $times and calculate the difference with creating DateTime objects and get the difference via diff():
<?php
$usr_breaks = ["skift_rast1" => "09:00-09:20", "skift_rast2" => "12:30-13:00"];
$times = array_map(function($v){
return array_combine(["start", "end"], explode("-", $v));
}, $usr_breaks);
//print differences
foreach($times as $time) {
$timeOne = new DateTime($time["start"]);
$timeTwo = new DateTime($time["end"]);
$interval = $timeOne->diff($timeTwo);
echo sprintf("%d hours %d minutes<br>", $interval->h , $interval->i);
}
?>
output:
0 hours 20 minutes
0 hours 30 minutes
I have an array,each element have a start_date and end_date.
I want to sum all the time periods between the two dates and divide them by 3 to get the average time period.
The Array
Array
(
[0] => Array
(
[start_date] => "2014-01-30 09:27:02"
[end_date] => "2014-01-30 16:29:38"
)
[1] => Array
(
[start_date] => "2014-01-28 09:27:02"
[end_date] => "2014-01-30 16:29:38"
)
[2] => Array
(
[start_date] => "2014-01-30 09:05:02"
[end_date] => "2014-01-30 12:12:38"
)
)
I need some thing like this:
$total=0;
foreach($array as $ar)
{
$created_dt=strtotime($ar[$start_date]);
$done_dt=strtotime($ar[$end_date]);
$runing_time= $created_dt - $done_dt - 2*3600;
$runing_time= date('H:i',$runing_time);
$total+=$runing_time;
}
$runing_time=$total/3;
what is a good way to do this?
thanks :)
You are making a fundamental mistake in trying to treat a time period as a date/time, you cannot use date() and its related functions for time periods.
The way to find the average of time periods is to sum the number of seconds and then divide that by the number of periods. The following function does this:-
function averageTime(array $times){
$total = 0;
foreach($times as $time){
$total += (new \DateTime($time['end_date']))->getTimestamp() - (new \DateTime($time['start_date']))->getTimestamp();
}
$avSeconds = $total/count($times);
$hours = floor($avSeconds/3600);
$avSeconds -= $hours * 3600;
$minutes = floor($avSeconds/60);
$avSeconds -= $minutes * 60;
$seconds = floor($avSeconds);
return "{$hours}h {$minutes}m {$seconds}s";
}
Plugging your example array into it:-
$times= array(
0 => Array(
'start_date' => "2014-01-30 09:27:02",
'end_date' => "2014-01-30 16:29:38",
),
1 => Array(
'start_date' => "2014-01-28 09:27:02",
'end_date' => "2014-01-30 16:29:38",
),
2 => Array(
'start_date' => "2014-01-30 09:05:02",
'end_date' => "2014-01-30 12:12:38",
),
);
echo "Average time = " . averageTime($times);
Output:-
Average time = 21h 44m 16s
Ref DateTime manual.
As shown at this answer it's ultra simple. :) (i have slightly modified it)
$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
$datediff = $now - $your_date;
$numberOfDays = floor($datediff/(60*60*24));
Now you just have to put it in foreach and sum in $numberOfDays in another variable.
And please remember to check if first date is lower than second date
Technically you are already correct.
But it order to have the given script to run propely you may have edit it to
$total=0;
foreach($array as $ar)
{
$created_dt=strtotime($ar['start_date']);
$done_dt=strtotime($ar['end_date']);
$runing_time= $created_dt - $done_dt - 2*3600;
$runing_time= date('H.i',$runing_time);
$total+=$runing_time;
}
$runing_time=$total/3;
so I only changed 3 thing.
first your $start_date and $end_date was an variable that was not existing.
and second if you want the average instead of : put . so it can be read as a double.
and if you want the variable $total to be the real value i would do this instead.
$runing_time= date('H',$runing_time).'.'.date('i',$runing_time)/60*100;
Hi i convert an collections of string comma separated 0 1 5, 2 3 15, 4 18 20 into an array using this functions as follow:
$openHrs = explode(",", $openHrs['open_hours']);
The end result are as follow:
Array ( [0] => 0 1 5 [1] => 2 3 15 [2] => 4 18 20 )
In this array 0 1 5 means Mon 1 am 5 am and 4 18 20 means Thur 6 pm 8 pm, so first digit represent weekday rest 2 digits represent hours in 24hrs format, now how can i output the existing array into this format?
Array ( [0] => Mon 1 am 5 am [1] => Tue 3 am 3 pm [2] => Thur 6 pm 8 pm )
Thanks
I would use array_map to get a filtered version. You can create dates using mktime() and format them using date(). I believe this should be the solution:
$filtered = array_map(function($incoming) {
$parts = explode(' ', $incoming);
return
date('D', mktime(0,0,0,1, $parts[0])) . ' ' .
date('g a', mktime($parts[1])) . ' ' .
date('g a', mktime($parts[2]));
}, $openHrs);
For the weekday, I suggest:
$weekday=array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');
foreach ($openHours As &$openHour) {
$foo = explode(' ',$openHour);
$openHour=$weekday[$foo].' '. // <-- write yourself a nice function to convert 24h to 12h, maybe there's something like this in PHP already?
}
Try this:
// This will be used for the week days
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
// Loop through each date
foreach($openHrs as &$temp) {
// Separate the numbers
$temp = explode(" ", $temp);
// Change from a 24 hrs clock to a 12 hrs clock
$temp[1] = $temp[1] > 12 ? $temp[1] - 12 . 'pm' : $temp[1] . 'am';
$temp[2] = $temp[2] > 12 ? $temp[2] - 12 . 'pm' : $temp[2] . 'am';
// Update the element
$temp = $weekdays[$temp[0]] . ' ' . $temp[1] . ' ' . $temp[2];
}
I would explode each Arrayelement again with a whitespace as Delimiter so you have a better array structure:
Array ( [0] => Array(0, 1, 5), [1] => Array(1, 3, 3) [2] => Array(4, 18, 18) )
If you have this structure there are probably several approaches. There might be a solution with date() and timestamps but Iam honestly not to sure about that. An other solution would be. Define another array with the Weekdays.
$weekdays = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
Then you can use the numbers that you have as index for that array to output the correct weekday.
The hours can you output with a little selfmade function ala:
function twentyFourHourToAmPM($number) {
if ($number > 12) {
return ($number - 12)." pm";
} else {
return $number." am";
}
}
Output everything should then work like this:
foreach ($openHrs as $key => $value) {
echo $weekdays[$value[0]]." ".twentyFourHourToAmPM($value[1])." - ".twentyFourHourToAmPM($value[2]);
}
i am implementing one application in which i have to display a time difference in total hour from end date to start date. suppose i have both start date and end date in timestamp.so how i will get the difference of date in total hour ?
now i am using the below code
$intervalo = date_diff(date_create(), date_create($end));
pr($intervalo);
and the output is like
DateInterval Object
(
[y] => 0
[m] => 1
[d] => 4
[h] => 18
[i] => 41
[s] => 2
[invert] => 0
[days] => 34
)
the above code show me the total hour baut the end date is greater then 1month it shows 1m in array . but i only want total number of hour only
can any one help me ?
thanks in advance
Don't use date_diff. Convert the dates to timestamps (which represent seconds), subtract the two, and divide by 3600.
$x = date_create();
$y = date_create($end)
$hours = ($y->getTimestamp() - $x->getTimestamp()) / 3600;
If you want hours, minutes, and seconds:
$x = date_create();
$y = date_create($end)
$diff = ($y->getTimestamp() - $x->getTimestamp());
$seconds = $diff % 60;
$diff = (int)($diff / 60);
$minutes = $diff % 60;
$diff = (int)($diff / 60);
$hours = $diff;
Hello I need to get N numbers from range between 2 big numbers, without the start and end numbers.
The (N) numbers must be on equal intervals... I will try to explain with small numbers:
<?php
$rangeStart = 0;
$rangeEnd = 100;
$n = 9;
In this example i need to get 10,20,30,40,50,60,70,80,90
I have try with 'for loop' but it is veeery slow, because I'm using range like 1207083600 ~ 1275512399
Will appreciate any help.
=====
This is what I call slow http://jsfiddle.net/pbF7N/1/
The start and end are timestamps and I need to extract 10 dates...
range() with its optional 3rd parameter to specify the step size...
range(10, 90, 10);
$range = range(10, 90, 10);
print_r($range);
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
[4] => 50
[5] => 60
[6] => 70
[7] => 80
[8] => 90
)
Something like this maybe:
function nrange($num, $start, $end)
{
$out = array(); $i = 0;
$interval = floor(($end - $start) / ($num + 1));
while ($i++ < $num )
$out[] = $start + $i * $interval;
return $out;
}
Consider first your example case. Your numbers broke up the range [0..100) into 10 equal intervals, [0..10), [10, 20), etc. up to [90..100).
Notice that the number of intervals is $n+1. So you see that each interval is of length ($rangeEnd - $rangeStart) / $n.
Using this information, you can use range to step across $interval numbers at a time, i.e.,
$interval = ($rangeEnd - $rangeStart) / $n;
$range = range($rangeStart, $rangeEnd, $interval);