calculating what second of the day an event occurred - php

I made some code that works, but it seems very inefficient. I am charting circles on a canvas to show when events happen during a work day. To do this I find the number of seconds of the day this happened, then convert this to minutes to show.
My question is why do I have to go strtotime(date('...',strtotime(time))) and call strtotime twice?
When I just had it like strtotime(date('Y-m-d',time) I would get a negative value.
<?php
$time_concerned = '2014-10-31 02:00:00';
$start_day_temp = strtotime(date('Y-m-d',strtotime($time_concerned)));
$end_day_temp = strtotime(date('Y-m-d H:i',strtotime($time_concerned)));
$num_seconds = $end_day_temp - $start_day_temp;
//divide by 60 to get minutes. divide in half to make fit on 720 scale.
$num_conv_minutes = (($num_seconds/60)/2);
echo ' ctx.fillStyle = "#00FF00";';
echo ' ctx.beginPath();';
echo ' ctx.arc('.$num_conv_minutes.'+ x_inbound,y_truck_arrivals,5,0,2*Math.PI);';
echo ' ctx.fill();';
echo ' ctx.stroke();';
?>

$time_concerned = '2014-10-31 02:00:00';
echo strtotime(date('Y-m-d',strtotime($time_concerned)));
echo "\r\n";
echo strtotime($time_concerned);
Try this. Fiddle.
These are almost the same thing. The only reason they're different is because when you convert the string to a date you're dropping the second minutes and hours, so PHP puts it to midnight and you lose the part that tells you you did all this at 2am.
This is useful the first time you use it because you need to get the timestamp of midnight to subtract from the other timestamp. However, the second time it's just redundant.
So here's how you do it..
$time_concerned = '2014-10-31 02:00:00';
$start_day_temp = strtotime(date('Y-m-d',strtotime($time_concerned)));
$end_day_temp = strtotime($time_concerned);

Related

PHP count time and divide in daytime/nighttime

I have been trying to figure this out for a week now. My wife has started a new taxi-company and she asked me to code a simple webpage for here where she could press a button to save a timestamp, then the press is again when she gets off work, it then creates a second timestamp
I have an MYSQL database with rows containing the start time and stop time. I have managed to use the diff function to see how much time it is between the two timestamps but now comes the tricky part.
Since it's different payments at different times of the day I need to divide the time at a shortened time.
Up to 19:00 she works "daytime" and after that, she works "nighttime" until 06:00 the other day, then there is "weekend daytime" and "weekend nighttime" as well.
So if she creates a timestamp whit the date and time: 2018-08-08 06:30 and then another timestamp at 2018-08-08 21:00, then I need a script that puts these data in ex "$daytimehours = 12" "$daytimeminutes = 30" and "$nighttimehours = 3" "$nighttimeminutes = 0"
I have managed to create a script that almost works, but it is several pages long, and it contains one if-statement for each different scenario daytime-nighttime, nighttime-daytime etc.
So do anyone has a good idea on how to solve this? or maybe just point me in the right direction. I would be happy to pay some money to get this to work.
My solution is
<?php
date_default_timezone_set('Asia/Almaty');
$endDate = '2018-08-08 21:00';
$startDate = '2018-08-08 06:30';
$nightmare = date('Y-m-d 19:00');
$startDay = date('Y-m-d 06:00');
$diffMorning = strtotime($nightmare) - strtotime($startDate);
$diffNight = strtotime($endDate) - strtotime($nightmare);
echo gmdate('H:i', $diffMorning) . "\n"; // this is the difference from start day till 19:00
echo gmdate('H:i', $diffNight); // this is the difference on nightmare
$total = $diffMorning + $diffNight;
echo intval($total/3600) . " hours \n";
echo $total%3600/60 . " minutes \n";
echo $total%3600%60 . ' seconds';
You can check via online compiler
given two dates stated as:
$endDate = '2018-08-08 21:00';
$startDate = '2018-08-08 06:30';
you can use the PHP Date extension to achieve the difference like this:
$start = date_create($startDate);
$end = date_create($endDate);
$boundnight = clone($end);
$boundnight->setTime(19,00);
$total_duration = date_diff($end,$start);//total duration from start to end
$day_duration = date_diff($boundnight,$start);//daytime duration
$night_duration = date_diff($end,$boundnight);// nighttime duration
you can use the format method to print a human readable string this way:
$total_duration=$total_duration->format('%H:%I');
$day_duration=$day_duration->format('%H:%I');
$night_duration=$night_duration->format('%H:%I');
At this step there is nothing left but you say you want to convert each duration in minutes.So let's build a function :
function toMinute($duration){
return (count($x=explode(':',$duration))==2?($x[0]*60+$x[1]):false);
}
Then you can use it this way:
$total_duration = toMinute($total_duration);
$day_duration = toMinute($day_duration);
$night_duration = toMinute($night_duration);
The output of
var_dump($total_duration,$day_duration,$night_duration) at this step is:
int(870)
int(750)
int(120)

Add 30 seconds interval in a given datetime

Need some help.
I am using PHP.
So I have coordinates data.
Specifically Longtitude and Latitude.
So let's say I have 15 data of Long and Lat to be inserted on a table.
However, the api gives me only a single datetime because these coordinates are in array.
For example:
[14.4364372;121.0125753, 14.4364375;121.0125755, 14.4364377;121.0125758, 14.436436;121.012574, 14.4364342;121.0125721, 14.4364326;121.0125704, 14.436433;121.0125707, 14.4364334;121.0125711, 14.4364338;121.0125716, 14.4364342;121.012572, 14.4364345;121.0125724, 14.4364348;121.0125728, 14.4364351;121.0125731, 14.4364353;121.0125733, 14.4364356;121.0125735]
So first you will explode it to get rid of the delimeter ','
And loop it to count how many are data,then explode again the delimiter ';' to count the long and lat given.
But it only have a single datetime.
What i want here is to insert these data including datetime but with interval of 30 seconds per insert.
How can i do that?
Expected output would be like this:
INSERT INTO table_gps(ticket,datetime,long,lat) VALUES(0,09/16/2016 03:30:26 pm, 14.4364363,121.0125745)
INSERT INTO table_gps(ticket,datetime,long,lat) VALUES(0,09/16/2016 03:30:56 pm, 14.4364364,121.0125746)
Here is my code:
$msg= 'YC GPS2~09/16/2016 13:29:46~-~[14.4364362;121.0125744, 14.4364363;121.0125745]';
if(strpos($msg,'YC GPS2')!==false){
//explode data
$explode=explode('~',$msg);
$ky=$explode[0];
$datetime=$explode[1];
$ticket=$explode[2];
$coords=$explode[3];
$coords=explode(',',$coords);
for($i=0;$i<count($coords);$i++){
$xpVal=$coords[$i];
if($xpVal){
$xp3=explode(';',$xpVal);
$lng=$xp3[0];
$lat=$xp3[1];
$lng=str_replace('[','',$lng);
$lat=str_replace(']','',$lat);
$time = date("m/d/Y h:i:s a", time() + 30);// where 30 is the seconds
echo "INSERT INTO GPS2(ticket,datetime,long,lat) VALUES(".$ticket.",".$time.",".$lng.",".$lat.") ";
}
}
}else{
echo '0';
}
Thanks.
In order to add how many seconds you want to particular date in PHP you can use the following.
$time = date("m/d/Y h:i:s a", time() + 30);// where 30 is the seconds
The following is really easy way to add days, minutes, hours and seconds to a time using PHP. Using the date function to set the format of the date to be returned then using strtotime to add the increase or decrease of time then after a comma use another strtotime passing in the start date and time.
//set timezone
date_default_timezone_set('GMT');
//set an date and time to work with
$start = '2014-06-01 14:00:00';
//display the converted time
echo date('Y-m-d H:i',strtotime('+1 hour +20 minutes',strtotime($start)));
Times can be entered in a readable way:
+1 day = adds 1 day
+1 hour = adds 1 hour
+10 minutes = adds 10 minutes
+10 seconds = adds 10 seconds

strtotime and weird results when calculating time differences (datetime)

I've been trying at this for a bit and can't get the damn code to work.. This is my first post, I've gone through a few, tried a million different ways.. I just want to get the difference in hours, then I'm set, I'll get the rest figured out..
Right now, it's giving me unusual answers (say there's a 2 hour difference, it'll give me 14 as an answer) Pardon my coding, I haven't done this in years and have no real formal training. I'll be as thorough as possible in my comments, and thanks a LOT. Any links appreciated. I have tried a LOT. Using PHP 5.3.something, and am pulling off a Wordpress 3.7.1 database.
Thanks in advance for the help for a beginner. I want to display "Updated x hours ago". Once I have the darned thing displaying the correct result, I'll figure the rest out.
//This is the current date, putting it into strtotime so everything is in the same format. It displays accurately.
$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDateHour = date("H", strtotime($currentDate . $currentTime));
// This is the date I'm pulling from the database, it only displays
// when in strtotime for some reason. It displays accurately to what is in the mySQL DB
$upDate = date("Y-m-d H", strtotime($row2[post_date]));
// Some variables to make life easier for later if statements if I ever get that far. Displays accurately.
$upDatehour = date("H", strtotime($row2[post_date]));
// trying simple subtraction
$hour = $currentDateHour - upDatehour;
// this is where the result is incorrect, what is wrong here? Any method I've tried gives me the same result, with or without strotime.. it's gotta be something simple, always is!
print strtotime($hour);
You can drastically simplify your code. I'd recommend refactoring it to use DateTime and specifically DateTime::diff().
$now = new DateTime();
$post = new DateTime($row2['post_date']);
$interval = $now->diff($post);
echo "Updated " . $interval->h . " hours ago";
Working example: http://3v4l.org/23AL6
Note that this will only show up to 24 hours difference. If you want to show all hours even for a difference of more than 24 hours, you'll need to figure in the days. Something like this:
$hours = $interval->h + ($interval->format("%a") * 24);
echo "Updated $hours hours ago";
Working example: http://3v4l.org/ilItU
If you are just trying to get the number of hours between two arbitrary times, the easiest way would be to get the difference in seconds of the two times, and then divide by 3600 to determine the number of hours between the two dates.
Here is a basic example:
<?php
$row2['post_date'] = '2013-12-02 07:45:38'; // date from database
$now = time(); // get current timestamp in seconds
$upDate = strtotime($row2['post_date']); // convert date string to timestamp
$diff = $now - $upDate; // subtract difference between the two times
$hours = floor($diff / 3600); // get the number of hours passed between the 2 times
echo $hours; // display result
Also, Wordpress has a built in function that may end up doing what your ultimate goal is, see wordpress function human_time_diff().
Example:
<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
Result:
2 days ago.
Example how to get difference between dates in hours:
$diff = date_diff(date_create(), date_create($row2['post_date']));
$hours = $diff->days * 24 + $diff->h;
If you wish to format output number with leading zeros, you can use sprintf() or str_pad() function. Example of sprintf() use for HH:mm format:
echo sprintf('%02d:%02d', $hours, $diff->i);
demo

Comparing DateTime?

I've been doing a good amount of research with this, and used a few codes to get to know how to make this work, but nothing has worked the way I wanted it to, or hasn't worked at all.
The code is:
<?php
$time1 = $user['last_active'];
$time2 = "+5 minutes";
if (strtotime($time1) > strtotime($time2)) {
echo "Online!";
}else{
echo "Offline!";
}
?>
It is supposed to compare the two variables, and find out if the last active variable is greater or less than 5 minutes, and if it is greater, appear offline. I do not know what's wrong as the NOW() updates on each page and stops if the user is not logged in. Any suggestions or help? Thanks.
The $time1 variable is coming from a fetched array that gets the ['last_active'] information that updates on each page.
I fixed my code, but it still doesn't work right, however, I think I have managed to get further than I was..
<?php
$first = new DateTime();
$second = new DateTime($user['last_active']);
$diff = $first->diff( $second );
$diff->format( '%H:%I:%S' );
if($diff->format( '%H:%I:%S' ) > (strtotime("5 minutes"))){
echo "Offline";
}else{
echo "Online";
}
?>
What can I do at this point?
Nobody pointed out that you actually have a bug. The "current time" will never be greater than "the current time +5 minutes"
Your first code sample will work right if you instead use "-5 minutes" as the "online threshold."
Also, comparing a timestamp without date to the output of strtotime() as you do in the second code is not a proper comparison. It has two problems:
Each time a new day comes around, the same time value will be repeated.
The output of strtotime is an integer representing seconds-since-epoch; the output of format() is a textual representation of hours:minutes:seconds within the current date.
As for your question how to calculate time between 2 dates / time, please view the solution on the following posts, that should give you enough information! (duplicate ? )
Calculate elapsed time in php
And here
How to get time difference in minutes in PHP
EDIT AS YOU PLEASE
<?
$first = new DateTime(); // this would hold your [last active]
//$first->modify("-6 minutes");
$second = new DateTime("NOW");
$difference = $second->diff( $first ); // second diff first
if ($difference->format('%i') > 5) { // comparing minutes only in example ( %i )
echo "The user is AFK";
} else {
echo "user might still be active";
}
?>

Get time from a date/time string

I have a date value stored in a variable. I need to extract the time part of the value in to a separate variable and then add/subtract time from it.
The date variable is set with date('YmdHis'), giving (for example) 20110805124000 for August 5th 2011, 12:40:00
From the value 20110805124000 (which is stored in the variable $fulltime), I need to store the time only in the format 12:40 (so ignoring the year, month, day and seconds and adding the colon between the hour and minute) in a variable called $shorttime. I then need to add a number of hours to that time (so for example +3 hours would change the value in the $shorttime variable to 15:40). The number of hours I need to add is stored in a variable called $addtime, and this value could be a negative number.
Is this easily doable? Could anyone help?
Thanks :)
$time = '2013-01-22 10:45:45';
echo $time = date("H:i:s",strtotime($time));
It will give the time 10:45:45 from datetime.
<?PHP
$addhours = 3;
$date = DateTime::createFromFormat('YmdHis', '20110805124000');
$shorttime = $date->format("H:i");
$newdate = $date->add(DateInterval::createFromDateString($addhours . "hours"));
$newtime = $newdate->format("H:i");
echo $shorttime . "<br />";
echo $newtime . "<br />";
?>
for your reference:
http://www.php.net/manual/en/datetime.createfromformat.php
http://www.php.net/manual/en/dateinterval.createfromdatestring.php
hello the way I usually do it is like this, maybe it's a bit long but it works for me...
$DateIn = new DateTime($In);
$DateOut = new DateTime($Out);
$HourOut = new DateTime($H_Out);
$FechaEntrada = $DateIn->format('d-m-Y');
$FechaSalida = $DateOut->format('d-m-Y');
$HoraSalida = $HourOut->format('H:i a');
the guide I used was the PHP one DateTime::format()

Categories