PHP - issue in adding 30 min to time - php

I am facing a weird issue, what I am trying to do here is to add 30 minutes to a specified time for multiple iterations using a while loop. Below is the code I am trying and not sure where it has gone wrong.
My Code
function session_slot_compare(){
$min_count = 3;
$time_now = '1:30';
$time_now_new = date('H:i', strtotime($time_now));
$duration_bits[0] = $time_now_new;
$i=0;
while($i<$min_count){
$time_now_new = date("H:i", strtotime('+30 minutes', $time_now_new));
$duration_bits[$i] = $time_now_new;
$i++;
}
print_r($duration_bits);}
Expected Output
I am actually expecting the output to be like Array ( [0] => 01:30 [1] => 02:00 [2] => 02:30 )
Actual Output
But I am getting the output as Array ( [0] => 01:30 [1] => 00:30 [2] => 00:30 )

The reason is that in the strtotime('+30 minutes', $time_now_new) you pass not a valid 2-nd argument. It should be a timestamp, but in your case it's a string. The shortest way to fix the problem is to add one more strtotime() call, like the following:
$time_now_new = date("H:i", strtotime('+30 minutes', strtotime($time_now_new)));
It'll work exactly in the way you expect.

Related

Stuck at date-format in seconds

first of all, I'm sorry for my english. I'm from germany.
Now my Problem:
I have a multiple array with some dates in it. I had to filter the first and the last date for every IP because I need the difference of both dates to know how much time the User on my website.
I did that and got all I need. Here is a part of my code output:
$ip_with_dates:
Array
(
[0] => Array
(
[ip] => 72.xx.xx.xx
[first_date] => 2015-10-12 00:10:15
[last_date] => 2015-10-12 01:10:51
)
[1] => Array
(
[ip] => 85.xx.xx.xx
[first_date] => 2015-10-12 00:10:19
[last_date] => 2015-10-12 01:10:56
)
I tried to get the time between those two dates with:
$visit_lenght = [];
foreach($ip_with_date as $key => $val){
$date1 = new DateTime($val['first_date']);
$date2 = new DateTime($val['last_date']);
$interval = $date1->diff($date2)->format('%h %m %s');
$visit_lenght[] = $interval;
}
what gives me this output:
Array
(
[0] => 1 36
[1] => 1 37
[2] => 0 3
[3] => 0 9
)
well but this isn't good to work with. I need the time in seconds not in H:m:s
but I really don't now how. This is a part of my project where I'm really fighting with. Maybe someone of you could help me with this.
I'm working with laravel. Normal PHP would make it too but if someone knows a solution in laravel, it would be nice as well!
thanks for any help!
To get time diff in seconds you need to convert your datetime objects to timestamps:
$visit_lenght = [];
foreach($ip_with_date as $key => $val){
$date1 = new DateTime($val['first_date']);
$date2 = new DateTime($val['last_date']);
$interval = $date1->getTimestamp() - $date2->getTimestamp()
$visit_lenght[] = $interval;
}
You may get timestamps of two dates and count the difference.
something like (in php).
$date1t = $date1->getTimestamp();
$date2t = $date2->getTimestamp();
$diff = $date2t - $date1t;
http://php.net/manual/en/datetime.gettimestamp.php
Try this way (general/basic way)
$visit_lenght = [];
foreach($ip_with_date as $key => $val){
$date1 = strtotime($val['first_date']);
$date2 = strtotime($val['last_date']);
//$interval = $date1->diff($date2)->format('%h %m %s');
$interval = $date2 - $date1;
$visit_lenght[] = $interval;
}
you can make this:
->format('Y-m-d H:i:s')
With DateTime() class of PHP, it is super simple to find difference between time. Here is an exmple:
<?php
$ip = "xxxx-xxx-xxx";
$t1 = DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-12 00:10:15');
$t2 = DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-12 01:10:51');
echo "User from IP {$ip} spent " . $t1->diff($t2)->format("%h hours, %i minutes and %s seconds");
?>

DateTime "diff"

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

What is the best way to subtract "after-hours" time from a date range to get an accurate "active" time?

I have 2 parallel arrays that contain mysql timestamps. The first array contains "Start" times, and the second array contains "Stop" times.
Example
Starts
Array ( [0] => 2014-12-05 12:21:29 [1] => 2014-12-10 07:14:17 [2] => 2014-12-10 12:43:47 [3] => 2014-12-12 07:39:28 [4] => 2014-12-12 08:13:30 )
Stops
Array ( [0] => 2014-12-08 08:08:37 [1] => 2014-12-10 10:13:37 [2] => 2014-12-12 07:18:53 [3] => 2014-12-12 08:10:39 [4] => 2014-12-12 08:27:26 )
I need to add the total times based off of all the starts and stops in each array, but I also need to subtract all the time that was "after-hours". This is for reporting purposes.
So let's say that any time after 4pm(16:00) and before 6am(06:00) needs to be removed from the total active time that will be reported.
I already have it subtracting weekend time, but I also need it to remove the "after-hours" time if it occurs after-hours on a weekday. The checks for weekday/weekend aren't a problem, but figuring out how to check if the time range contains hours that were after business hours is what is stumping me.
Here is how I am subtracting the weekend time:
function getWeekendSeconds($starts, $stops){
$count = 0;
$secondsToSubtract = 0;
$secondsInDay = 86400;
if(count($starts) > count($stops)){
while(count($starts) != count($stops)){
array_pop($starts);
}
}
foreach($starts as $start){
$stop = $stops[$count];
$startTime = strtotime($start);
$stopTime = strtotime($stop);
while($startTime < $stopTime){
$dayNum = date('N', strtotime(date("Y-m-d H:i:s", $startTime)));
if($dayNum == 6 or $dayNum == 7){
$secondsToSubtract += $secondsInDay;
}
$startTime = strtotime(date("Y-m-d H:i:s", $startTime) . " +1 day");
}
$count = $count + 1;
}
return $secondsToSubtract;
}
I was thinking of doing something similar to calculate the after-hours time, but I'm having trouble wrapping my head around it.
Would I just take the start time and add time to it and check it each time to see if it's greater than the business closing time? Is it simpler than I'm making it? Is there a mysql solution I'm not aware of?
Thanks in advance!

php strtotime array sorting issue

I'd like to start off by saying thank you for taking the time to read this post. I hope that someone will be kind enough to help me as I am just starting to learn PHP. Please forgive me if I do not use the correct terminology to describe my issue.
I'm having an issue sorting my array.
My array looks like this:
<?php
$rooms = array(
strtotime('next monday')=>array('day'=>'monday', 'abbrev'=>'Mon'),
strtotime('next tuesday')=>array('day'=>'tuesday', 'abbrev'=>'Tue'),
strtotime('next wednesday')=>array('day'=>'wednesday', 'abbrev'=>'Wed'),
strtotime('next thursday')=>array('day'=>'thursday', 'abbrev'=>'Thu'),
strtotime('next friday')=>array('day'=>'friday', 'abbrev'=>'Fri'),
strtotime('next saturday')=>array('day'=>'saturday', 'abbrev'=>'Sat'),
strtotime('next sunday')=>array('day'=>'sunday', 'abbrev'=>'Sun'));
ksort($rooms);
foreach($rooms as $room_timestamp=>$room_info) {
if (time() > strtotime($room_info['day'])) {
print ($form->checkBox($model,'space_'.$room_info['day'], array('value' => strtotime($room_info['day']))) . $form->labelEx($model,$room_info['abbrev'].' ' . date('n/j', strtotime($room_info['day']))) . '<br />');
} else {
print ($form->checkBox($model,'space_'.$room_info['day'], array('value' => strtotime('next '.$room_info['day']))) . $form->labelEx($model,$room_info['abbrev'].' ' . date('n/j', strtotime('next '.$room_info['day']))) . '<br />');
}
}
echo "<pre>".print_r($rooms,1)."</pre>";
?>
And it is outputting the checkboxes in this order:
Mon 6/3Tue 6/4Wed 6/5Thu 6/6Fri 6/7Sat 6/8Sun 6/2
I'm trying to get today (in this case Sun 6/2) to show first, and then the next 6 days to show in order.
When I use print_r to display the raw output, it looks like this:
Array
(
[1370239200] => Array
(
[day] => monday
[abbrev] => Mon
)
[1370325600] => Array
(
[day] => tuesday
[abbrev] => Tue
)
[1370412000] => Array
(
[day] => wednesday
[abbrev] => Wed
)
[1370498400] => Array
(
[day] => thursday
[abbrev] => Thu
)
[1370584800] => Array
(
[day] => friday
[abbrev] => Fri
)
[1370671200] => Array
(
[day] => saturday
[abbrev] => Sat
)
[1370757600] => Array
(
[day] => sunday
[abbrev] => Sun
)
)
Sunday is showing a larger time stamp than the other days, is this because it is somehow outputting next Sunday's time stamp instead of today's time stamp?
Initially I was creating the checkboxes and labels using two if/else statements for each day. Unable to sort them this way I attempted to create an array which is what I am now having trouble with.
My original code (this example is for Tuesday) looked like this:
<?php
if (time() > strtotime('tuesday'))
{
echo $form->checkBox($model,'space_tuesday', array('value' => strtotime('tuesday')));
}
else
{
echo $form->checkBox($model,'space_tuesday', array('value' => strtotime('next tuesday')));
}
?>
<?php
if (time() > strtotime('tuesday'))
{
echo $form->labelEx($model,'Tues ' . date('n/j', strtotime('tuesday')));
}
else
{
echo $form->labelEx($model,'Tues ' . date('n/j', strtotime('next tuesday')));
}
?>
Is there a better way to create an array to achieve this and sort in the correct order? Am I missing something simple with the array I've already created?
Any help that you could provide would be greatly appreciated.
Thank you.
As far as I understand it, for what you want to achieve, you're overcomplicating things:
for ( $i=0; $i<6; $i++ ) {
echo date('D n/j', strtotime("+$i day")) . '<br />';
}
Days naturally progress in the way you want, so you might as well use that fact — and avoid sorting all together. You can also make use of php's date formatting to avoid having to store shortforms of days too.
update
This should give you an idea of what you can do, I'd suggest you read up on what you can generate using PHP's date function — it's rather useful :)
http://uk1.php.net/manual/en/function.date.php
for ( $i=0; $i<6; $i++ ) {
/// pull out our datetime into a variable
$datetime = strtotime("+$i day");
/// wrap it with an array ready for checkBox()
$value = array('value' => $datetime);
/// generate the different parts we may need from date()
list($day, $formatted) = explode(',', date('l,D n/j', $datetime));
/// place those parts where we need them
echo $form->checkBox($model, "space_" . strtolower($day), $value);
echo $form->labelEx($model, $formatted));
}
Sunday is showing a larger time stamp than the other days, is this because it is somehow outputting next Sunday's time stamp instead of today's time stamp?
Yes, this is what you coded: strtotime('next sunday')
Try using numbers if you want today and next 6 days, e.g.+1 day, ..., +6 days: http://www.php.net/manual/en/dateinterval.createfromdatestring.php
Change 'next sunday' to 'sunday', put it in as the first array element and you should be good..

Countdown to sunday

I am currently looking at creating a script for my site that will count down to sunday of that week, every week.
Example:
The user visits the site on a saturday at 11:30am, they will be greeted with:
"The next time this page will be updated is in 0 days, 12 hours and 30 minutes."
Any ideas?
You can use this little trick to get a timestamp for midnight next Sunday:
$sunday = strtotime('next Sunday');
See this answer for how to format it into something useful. Right now I get this:
print_r(dateDifference($sunday, time()));
Array
(
[years] => 0
[months_total] => 0
[months] => 0
[days_total] => 0
[days] => 0
[hours_total] => 4
[hours] => 4
[minutes_total] => 256
[minutes] => 16
[seconds_total] => 15387
[seconds] => 27
)
I am using similar to this solution in one of my pojects. You can use it like this:
ago(strtotime("next sunday")) but you need to change $difference = $now - $time; to $difference = $time - $now;
Here's one solution:
http://jsfiddle.net/foxbunny/xBE7L/
It also automatically updates every second.
Edit: I've included the offset parameter, and you use it to supply the difference between user's and server's time-zone if necessary.

Categories