PHP - Difference between two times - php

I've created a timing system for a charity race. I'm trying to find the difference between the start time and the finishers time using PHP. I'm not sure I'm recording the times correctly, but this is the start time i just recorded...
20180808180653
And this is a finisher time...
20180808180654
The difference between them is roughly 1 hour 24, but when i use...
date('h:i:s', $finshTime-$startTime)
I get 03:24:20 not 01:34:20.
Can someone please help?

The date method accepts as "integer Unix timestamp". You are supplying instead a number of seconds (1 in your example).
$start = '20180808180653';
$end = '20180808180654';
$diff = $end - $start;
var_dump($diff); //1
$d = date('h:i:s', $$diff);
var_dump($d); //04:00:01
//the above is wrong. You need to try something like the code below
$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$interval = $dStart->diff($dEnd);
var_dump($interval->format('%h:%i:%s'));
I'd be leery using a string representation of a datetime that looks like that. Convert the whole thing into a date format that makes sense like yyyy-mm-dd hh:mm:ss, or a valid unix time stamp.
Your first approach isn't that far off, you just need to use a strtotime function. I'd guarantee that you can first make an accurate Date or Unix time representation of those strings you are using. Rest should fall into place.

First check if the type of $finshTime and $startTime are integer.
you can use get variable type:
gettype($startTime);
if this is the case try this with ():
$diff_date = date('h:i:s', ($finshTime - $startTime) );
if $startTime and $finshTime are string try this:
$diff_date = date('h:i:s', (strtotime($finshTime) - strtotime($startTime)) );

Related

Get difference between 2 date_time in minutes

Im trying to get the difference between 2 differente dates in minutes, but is not outputting correctly.
Ex:
$then = "2017-01-23 18:21:24";
//Convert it into a timestamp.
$then = strtotime($then);
//Get the current timestamp.
$now = time();
//Calculate the difference.
$difference = $now - $then;
//Convert seconds into minutes.
$minutes = floor($difference / 60);
echo $minutes;
Is outputting 611 minutes, and is wrong since from "2017-01-23 18:21:24" to "2017-01-24 12:36:24" it past much more than 611 minutes. Is my code incorrect?
Try to set your default timezone
date_default_timezone_set('Europe/Copenhagen');
Ofc change Europe/Copenhagen for the one that suits your needs.
If you are using or able to use PHP 5.3.x or later, you can use its DateTime object functionality:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
You can play with the format in a variety of ways, and once you have dates in DateTime objects, you can take advantage of a lot of different functionality, for example comparison via normal operators. See the manual for more: http://us3.php.net/manual/en/datetime.diff.php
I've checked your code it works perfectly So if have any doubt see your result
But you got wrong, so to ignore this set your timezone.

How to compare current time with old time in PHP

I have stored date field at DB.
In PHP, i am getting that field and converted into date.
I want to compare that time with current time. If that difference is above 60 minutes. It will return some value.
I dont know how to write logic for that
$lastUpdatedField = $rows_fetch['lastUpdatedTime'];
$lastUpdatedDate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
I have old date&time is in $lastUpdatedDate variable, and current time is in $nowDate.
How to compare these two
$interval = $nowDate->diff($lastUpdatedDate);
echo $interval->h;
DateDiff: http://www.php.net/manual/en/datetime.diff.php
DateInterval: http://www.php.net/manual/en/class.dateinterval.php
Had The same problem earlier its actually quit simple
heres the piece where you declare your variables
$lastUpdateddate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
Then you have to convert them to second - format so that you can do math with them
To do that use strtotime
$Diff = strtotime($lastUpdatedDate) - strtotime($nowDate);
Then just check to see if the difference in time is more then 60 minutes,
So devide by 60 seconds to get minutes and by 60 to get hours
if ($diff/60/60 <= 1){
//do your thing here
{
First convert the current time and old time to one unit like Unix timestamp passing it through strtotime(). Then differentiate both the timestamp to get the difference between two times.
$difftime = strtotime(date('Y-m-d H:i:s')) - strtotime($rows_fetch['lastUpdatedTime']);
Then convert the difference to days as follows :
$days=$difftime/24*60*60;
Once you get the days you can get the minutes from it as below to compare to meet your need.
$timediff = $days * 24 * 60;

Modify microseconds of a PHP DateTime object

I have a PHP DateTime object with microseconds created as follows:
$time = microtime(true);
$microseconds = sprintf('%06d', ($time - floor($time)) * 1000000);
$dt = new DateTime(date('Y-m-d H:i:s.' . $microseconds, $time));
How can I modify the microseconds value of $dt, without creating a completely new DateTime instance?
You can't.
There are three methods that can modify the value of a DateTime instance: add, sub and modify. We can rule out add and sub immediately because they work in terms of a DateInterval which does not have sub-second precision.
modify accepts a string in one of the standard recognized formats. Of those formats, only the relative ones are of interest here because the other ones work in an absolute manner; and there is no relative format that allows tweaking the msec part (that unit is not recognized).
as of PHP 7.1
DateTime::setTime() supports microseconds.
This seems to have been available since 7.1.0-rc4
$dt = new DateTime('2020-01-01 0:00');
$dt->modify('+500 ms'); // Milliseconds.
$dt->modify('+123456 usec'); // Microseconds.
$dt->modify('+123456 microseconds'); // This works too.
It's mentioned here in the manual.
Manually creating a DateTime object with micro seconds:
$d = new DateTime("15-07-2014 18:30:00.111111");
Getting a DateTime object of the current time with microseconds:
$d = date_format(new DateTime(),'d-m-Y H:i:s').substr((string)microtime(), 1, 8);
Difference between two DateTime objects in microseconds (e.g. returns: 2.218939)
//Returns the difference, in seconds, between two datetime objects including
//the microseconds:
function mdiff($date1, $date2){
$date1sec = strtotime($date1->format('d-m-Y H:i:s.u'));
$date2sec = strtotime($date2->format('d-m-Y H:i:s.u'));
//Absolute val of Date 1 in seconds from (EPOCH Time) - Date 2 in seconds from (EPOCH Time)
$secdiff = abs($date1sec-$date2sec);
//Creates variables for the microseconds of date1 and date2
$micro1 = $date1->format("u");
$micro2 = $date2->format("u");
if (($date1sec<$date2sec && $micro1>$micro2)||($date1sec>$date2sec && $micro1<$micro2)){
$microdiff = abs(1000000 - abs($micro1-$micro2));
$secdiff = $secdiff - 1;
} else {
$microdiff = abs($micro1 - $micro2);
}
//Creates the variable that will hold the seconds (?):
$difference = $secdiff.".".$microdiff;
return $difference;
}
Essentially it finds the difference for the DateTime Objects using strtotime and then adding the extra microseconds on.
Do you need me to create add and sub?
i had a similar problem and ended up having to wrap the whole thing
https://gist.github.com/chandeeland/9817516
For the people only in need to zero-out microseconds (I had to because of database layer) here's the snippet I ended up using:
$format = "Y-m-d H:i:s e";
$now = (new \DateTime())->format($format);
$dateTime = \DateTime::createFromFormat($format, $now);
Note that using $format = 'c', ISO 8601, will not work, as explained here (https://stackoverflow.com/a/10478469/8119317).

count hours remain between 2 dates with php

i have this dates
$dt_occ = mysql_result($info,0,"occ_data");
$dt_occ = strtotime($dt_occ);
$dt_occ = strtotime('+1 day' , $dt_occ);
$dt_unico = date('d/m/Y H:i',$dt_occ);
$dt_il = date('d/m/Y',$dt_occ);
$dt_alle = date('H:i',$dt_occ);
I need to know how many hours remain between now and $dt_unico
Take a look at the DateTime classes, they are much more flexible that strtotime() and date() (IMHO). Something like this will work for you:-
function getDiffInHours(\DateTime $earlierDate, \DateTime $laterDate)
{
$utc = new \DateTimeZone('UTC');
//Avoid side effects
$first = clone $earlierDate;
$second = clone $laterDate;
//First convert to UTC to avoid missing hours due to DST etc
$first->setTimezone($utc);
$second->setTimezone($utc);
$diff = $first->diff($second);
return 24 * $diff->days + $diff->h;
}
Use it like this for example:-
$hours = getDiffInHours(new \DateTime($dt_occ), (new \DateTime($dt_occ))->modify('+ 1 day'));
var_dump($hours); //24
I think this will work for you.
$dt1 = new DateTime($dt_occ);
$dt2 = new DateTime($dt_occ);
$dt2->modify("+1 day");
$interval = $dt2->diff($dt1);
echo $interval->hours;
If you're using PHP5.5 you can simply this a little bit:
$dt1 = new DateTimeImmutable($dt_occ);
$dt2 = $dt1->modify("+1 day");
$interval = $dt2->diff($dt1);
echo $interval->hours;
Since $dt_unico is derived from $dt_occ, which is a timestamp and time() gives the current time, also as a timestamp, subtracting the former from the latter will give the interval between them, in seconds.
Now, an hour is 60*60=3600 seconds, so:
$interval=(time()-$dt_occ)/3600;
Some notes, though:
I assumed that $dt_occ refers to the past. Future dates will give negative results, so if that's the case, switch the subtraction operands.
The above will give a floating point result. For an integral result, use the appropriate rounding function depending on the desired rounding method.

PHP| arrays with times

I need to compare bentween a time taken from a database to the current time.
$DBtime = "2013-10-29 17:38:55";
this is the format of the arrays in the database.
How can I compare it with the current time?
Im not sure how, but maybe converting DBtime to Unixtime then:
(CurrentUnixTime - dbUnixTime) = x
Or maybe, we can take the 17:38 and compare it somehow with date("G:i");
Thank you! I hope you understand what I mean.
You can transform it into a UNIX timestamp using strtotime and then subtract the current timestamp by it.
$DBtime = "2013-10-29 17:38:55";
$db_timestamp = strtotime($DBtime);
$now = time();
$difference = $now - $db_timestamp;
echo $difference;
This will give you the difference in seconds.
You can convert the DBtime string to a unix timestamp in PHP using strtotime. In MySQL, you can use UNIX_TIMESTAMP when querying the column.
time() - strtotime($DBtime)
$date1 = new DateTime('2013-10-29 17:38:55');
$date2 = new DateTime('2013-11-29 18:28:21');
$diff = $date1->diff($date2);
echo $diff->format('%m month, %d days, %h hours, %i minutes');
$DBtime = "2013-10-29 17:38:55";
// Set whatever timezone was used to save the data originally
date_default_timezone_set('CST6CDT');
// Get the current date/time and format the same as your input date
$curdate=date("Y-m-d H:i:s", time());
if($DBtime == $curdate) {
// They match, do something
} else {
// They don't match
}

Categories