Stuck at date-format in seconds - php

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");
?>

Related

PHP - issue in adding 30 min to time

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.

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

PHP Date: Every monday next 3 weeks (Google Calendar remake)

I'm making a CRM-system, and I now need to offer people to make recurring events. For that they will have to fill out if it's daily, weekly, monthly or yearly, and everything like when you do it in Google Calendar.
But how will I get the dates in an array for "monday next 3 weeks" for example?
$int_count = 3; // How many to repeat
$date = new \DateTime('next monday');
$result = array($date->format('Y-m-d'));
for ($i=1; $i<$int_count; $i++) {
$result[] = $date->modify('+1 week')->format('Y-m-d');
}
print_r($result);
Result:
Array
(
[0] => 2015-01-26
[1] => 2015-02-02
[2] => 2015-02-09
)
The best way is to use DateTime and DatePeriod classes. It's the most correct way to deal with dates now. It deals with timezones and DST shifts automatically. It's just the way you must do it.
$daterange = new DatePeriod(new DateTime('next monday'), new DateInterval('P1W'), 2);
$dates = [];
foreach($daterange as $date) $dates []= $date->format("Y-m-d H:i:s");
print_r($dates);
The result will be:
Array
(
[0] => 2015-01-26 00:00:00
[1] => 2015-02-02 00:00:00
[2] => 2015-02-09 00:00:00
)

Calculating difference between dates

I need your help in how to subtract the last_modified and the final_manuscript_date in the following array:
Array (
[chapters_id] => 10736
[last_modified] => 2010-12-21 15:01:55
[steps_id] => 3
[sub_step_id] => 0
[steps_position] => 1
[final_manuscript_date] => 2010-09-27
)
So I can in this case get a value of N days between the dates 2010-12-21 and 2010-09-27?
Can't you simply do:
$diff = strtotime($arr["final_manuscript_date"]) - strtotime($arr["last_modified"]);
$days = $diff / 84600; // to get # of days, you can round them off or use ceil/floor
If you have 5.3+:
$date1 = new DateTime("2010-09-27");
$date2 = new DateTime("2010-12-21");
$interval = $date1->diff($date2);
echo $interval->d //returns days.
Have you checked strtotime?
http://php.net/manual/en/function.strtotime.php

PHP array question

I was wondering how can I turn the following date into an array.
PHP code.
$current_date = date('Y-m-d H:i:s'); //current date
$current_date = array(date('Y-m-d H:i:s'));
The built-in php function strptime() converts a date to an array. See the linked documentation for details about the structure of the array it produces.
I think you want to get the components of the function return into an array.
// Method one
$current_date = array(date('Y'),date('m'),date('d'),date('H'),date('i'),date('s'));
// Method two
$current_date = date('Y-m-d H:i:s'); //current date
$exploded_current_date = explode(" ", $current_date);
$date = explode("-",$exploded_current_date[0]);
$time = explode(":",$exploded_current_date[1]);
$current_date = array_merge($date,$time);
Update:
// Method three
$current_date = getdate();
/*
Returns
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)
*/
Here is an example.
<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);
echo "$strf\n";
print_r(strptime($strf, $format));
?>

Categories