How to get the SHORTEST difference between two times in PHP? - php

I am currently getting the difference between two times in minutes like this below, and it works fine...
$time1 = strtotime($firsttime);
$time2 = strtotime($secondtime);
$interval = abs($time2 - $time1);
$diffinminutes = round($interval / 60);
But say for example...
$firsttime = 02:05
$secondtime = 20:05
This calculation would return 1080 minutes (18 hours x 60 minutes).
I would like to be able to get the shortest difference, based on the time being a connected circle (i.e. like a clock haha).
So in the example above, I would rather it "go backwards" from 02:05 until it hit 20:05 and thus return 360 minutes (6 hours x 60 minutes).
In other words, I'm looking to get the shortest difference, regardless of which direction we go to find it.
Hopefully this makes sense.
Any insight on how to accomplish this would be appreciated, thank you!

(This assumes your inputs are just times and not timestamps.)
If your result is greater than 12 hours, then just subtract it from 24:
if ($result > 720) {
$result = 1440 - $result;
}
You might want to change the > to >= depending on which side you want ties to fall on.

Related

Counting days from two date fields, start counting from 1 instead of 0?

I'm using a PHP function to count days between start date and end date for courses on a website. The function itself works flawless, however I'd like the counting to start from 1 as standard instead of 0.
My code looks like this
function dateDifference($start_date, $end_date) {
// calulating the difference in timestamps
$diff = strtotime($start_date) - strtotime($end_date);
// 1 day = 24 hours
// 6 * 60 * 60 = 86400 seconds
return ceil(abs($diff / 86400));
}
I guess the answer to this question is pretty straight forward however I'm not that wandered in PHP.
Thanks!
After just some mins I managed to solve the mystery myself and now I feel pretty dumb since the solution really is super simple.. code below.
return ceil(abs($diff / 86400) +1);
So what I did was to add +1 next to the calculation meaning the $diff array will add 1 day to however many days the calculation will count to.
Might help someone!

Finding the difference between 2 times in hours:min

I'm trying to find the difference between 2 times obtained from a sql query:
$WakeTime = '05:00:00'; //this is data of today pulled from sql.
$SleepTime = '20:30:00'; //this is data of yesterday pulled from sql.
The result I'm looking for is like:
$Sleep = 24 + $WakeTime - $SleepTime;
so that $Sleep should give '08:30';
Which it's the correct method to get this?
Try something like this, maybe it will be for you.
$result = gmdate("H:i", 86400 - strtotime($SleepTime) - strtotime($Waketime));
output: 08:30
$sleep = gmdate("H:i", 86400 - strtotime($row["SleepTime"]) + strtotime($row["WakeTime"]));
This worked consistently. The time, pulled from sql, formats 00:00 Hrs as 1584297000. So just in case the seconds are required by anyone, this is the number you need to subtract from your time. Probably this differs from TimeZone to TimeZone; you will need to check.

Display Database Entities within a specific time frame

I want to display content from the database with dates up to 2hours ahead of time.
Example:
2018-11-09 20:00:00.000000
2018-11-08 19:00:00.000000
2018-11-06 19:00:00.000000
2018-11-06 18:00:00.000000
Lets say the time and date is
Nov 6th at 6pm. I want the bottom two entries to be displayed and the two future dates to not show until the current time is within 2hours of that time.
My code is as follows:
$cT = strtotime($row3['MissionTime']) - strtotime("now");
if($cT <= strtotime('-2 hours')) {
echo $row3['MissionTime']."<br>";
}
I've tried several different ways but I can't seem to get this to work right. Help and tips?
The reason your code doesn't work is that strtotime returns a number of seconds since the unix epoch. When you subtract two results of strtotime you will get a number of seconds difference which is as you expect. However you cannot compare that value to strtotime('-2 hours') as the output of that will be the timestamp for 2 hours before now (which right now is 1541539906), so the test will always pass. You should just compare it to 7200 instead (I'm pretty sure based on your question description that +7200 is more appropriate than -7200). so change
if($cT <= strtotime('-2 hours')) {
to
if($cT <= 7200) {
Note that it is almost certainly better to do this in your query. Try adding a condition on your time column as something like
WHERE MissionTime <= NOW() + INTERVAL 2 HOUR
And then you won't need to check in the PHP at all.
strtotime() returns a timestamp in seconds. Subtracting two timestamps gives you a difference between those two timestamps, in seconds.
So if strtotime($row3['MissionTime']) is a timestamp that's 1.5 hours in the future, and you subtract strtotime("now") from it, you end up with a difference of 5400 seconds (60 seconds * 60 minutes * 1.5 hours).
strtotime('-2 hours') gives you the timestamp for 2 hours ago, which is currently somewhere around 1.5 billion. This is not very useful for your situation.
Here are two ways to modify your code:
$cT = strtotime($row3['MissionTime']) - strtotime("now");
if($cT <= 7200) {
echo $row3['MissionTime']."<br>";
}
If the difference between $row['MissionTime'] and now is less than 7200 seconds (60 seconds * 60 minutes * two hours), $row3['MissionTime'] is either in the past or it's within the next two hours.
Alternatively:
if(strtotime($row3['MissionTime']) <= strtotime('+2 hours')) {
echo $row3['MissionTime']."<br>";
}
Basically the same, but perhaps more readable if you're not planning to use $cT for anything else. This simply checks if $row3['MissionTime'] is earlier than whatever time it will be in +2 hours.

Cannot figure out php date() timestamps for two timestamps

With PHP, I am trying to convert a bunch of numbers into a a readable format, the thing is, I have no idea how/what format these are in or can be parsed in using the date() or time() functions in php. there are two of these as well.
(they're built from a total time spent online and time since last log-on)
onlinetime : 1544946 = 2w 3d 21h 9m
lastonline : 1397087222 = 1h 32m
does anyone know the way to get the two different times from the two different timestamps?
If you have a Unix timestamp, take a look at Convert timestamp to readable date/time PHP. The PHP documentation is here: http://php.net/manual/en/function.date.php.
For the online time, you could do modulo arithmetic to figure out the values for each, and then just make a string out of the result. Someone may have a nicer suggestion for this though.
I think John is right, the first is the number of seconds in the timespan listed. And the second certainly looks like a unix timestamp to me. So here's how you can get what you want from these sets of numbers:
1) For the first number, simply divide the number by the seconds in a given time span and use floor():
$timeElapsed = 154496; // in this case
$weeksElapsed = floor($timeElapsed / 604800);
$remainder = $timeElapsed % 604800;
$daysElapsed = floor($remainder / 86400);
etc...
2) For the second number, you can do the same thing by first getting the current timestamp and then subtracting the given timestamp from it:
$lastOnline = 1397087222; // again, in this case
$currentTimestamp = time();
$elapsedSinceLastLogin = $currentTimestamp - $lastonline;
$weeksSinceLastLogin = floor($elapsedSinceLastLogin / 604800);
etc...

Find difference between now and a file's last change time in PHP

I have a file called "file.txt".
I get its last change time with this:
$lastTime = filemtime("file.txt");
Then I make
$lastDate = date("Y-m-d",strtotime( $lastTime ));
$todaysDate = date("Y-m-d",strtotime('now'));
Then I substract lastDate from todaysDate and find the difference.
Is there a quicker way to do this?
I don't want to check whether the difference of seconds is >= 86400 or not.
For example the difference between these two dates must be "1".
2013-03-31 10:00
2013-03-30 19:00
If i check for the difference of seconds I will have 54K seconds, which is smaller than 86400 seconds.
Get the difference in seconds, then convert to days and round the result.
$diff = time()-filemtime("file.txt");
$days = round($diff/86400);
You could also use floor or ceil in place of round depending on exactly how you want to handle partial days.

Categories