count hours remain between 2 dates with php - 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.

Related

PHP - Difference between two times

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

Having a hard time understanding how to manipulate date and time in PHP

I'm really not grasping how dates and times get formatted in PHP for use in mathematical equations. My goal is this;
Get a date and time from the database;
// Get array for times in
$sth = mysqli_query($conn,"SELECT * FROM ledger ORDER BY ID");
$timeins = array();
while($r = mysqli_fetch_assoc($sth)) {
$timeins[] = $r["timein"];
//OR
array_push($timeins, $r['timein']);
}
And then find the distance between the current time and the variable in the array, $timeins[0], and then put the minutes, hours, and days difference in separate simple variables for later use. These variables will be used on their own in if statements to find out if the person has passed certain amounts of time.
edit: the format of the dates being returned from the DB is in the default TIMESTAMP format for MySQL. E.g. 2018-08-06 17:38:37.
It is also possible to perform datetime operations in SQL, to get a difference between two datetime/timestamp values in days, hours, minutes... We can use expressions in the SELECT list, to return the results as columns in the resultset.
Ditching the SELECT * pattern, and specifying an explicit list of expressions that we need returned:
$sql = "
SELECT t.id
, t.timein
, TIMESTAMPDIFF(DAY ,t.timein,NOW()) AS diff_days
, TIMESTAMPDIFF(HOUR ,t.timein,NOW()) AS diff_hours
, TIMESTAMPDIFF(MINUTE ,t.timein,NOW()) AS diff_minute
FROM ledger t
ORDER BY t.id ";
if( $sth = mysqli_query($conn,$sql) ) {
// execution successful
...
} else {
// handle sql error
}
You should use the DateTime class in PHP to do any date manipulation. You can convert a string representation of a MySQL format time to a PHP DateTime object using
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
Also you can create a DateTime object representing the current time using the constructor with no argument:
$now = new DateTime();
To get the difference between two dates as a DateInterval object, use the builtin diff method:
$diff = $now->diff($date);
As a complete example:
$now = new DateTime();
$mysqldate = '2018-04-03 12:30:01';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
$diff = $now->diff($date);
$diff_days = (int)$diff->format('%a');
$diff_hours = $diff->h;
$diff_minutes = $diff->m;
echo "$diff_days days, $diff_hours hours, $diff_minutes minutes";
Output:
125 days, 9 hours, 4 minutes
Note that you have to use $diff->format('%a') rather than $diff->d to get the days between two dates, as $diff->d will not include the days in any months between the two dates (in this example it will return 3 for today being August 6).
Using the DateTime Class in php is the best way to get accurate results.
$dateNow = new DateTime('now');
$dateIn = DateTime::createFromFormat('d-m-Y H:i:s', $timeins[0]);
$interval = $dateNow->diff($dateIn);
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
$deltaDays = $interval->d;
$deltaHours = $interval->h;
...
You have to make sure the input format for you DB date is correct, in this case, I assumed d-m-y H:i:s, and then you can output in any format you need as well, as shown in the date docs: http://php.net/manual/en/function.date.php

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 get millisecond between two dateTime obj?

How to get millisecond between two DateTime objects?
$date = new DateTime();
$date2 = new DateTime("1990-08-07 08:44");
I tried to follow the comment below, but I got an error.
$stime = new DateTime($startTime->format("d-m-Y H:i:s"));
$etime = new DateTime($endTime->format("d-m-Y H:i:s"));
$millisec = $etime->getTimestamp() - $stime->getTimestamp();`
I get the error
Call to undefined method DateTime::getTimestamp()
In the strict sense, you can't.
It's because the smallest unit of time for the DateTime class is a second.
If you need a measurement containing milliseconds then use microtime()
Edit:
On the other hand if you simply want to get the interval in milliseconds between two ISO-8601 datetimes then one possible solution would be
function millisecsBetween($dateOne, $dateTwo, $abs = true) {
$func = $abs ? 'abs' : 'intval';
return $func(strtotime($dateOne) - strtotime($dateTwo)) * 1000;
}
Beware that by default the above function returns absolute difference. If you want to know whether the first date is earlier or not then set the third argument to false.
// Outputs 60000
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31");
// Outputs -60000 indicating that the first argument is an earlier date
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31", false);
On systems where the size of time datatype is 32 bits, such as Windows7 or earlier, millisecsBetween is only good for dates between 1970-01-01 00:00:00 and 2038-01-19 03:14:07 (see Year 2038 problem).
Sorry to digg out an old question, but I've found a way to get the milliseconds timestamp out of a DateTime object:
function dateTimeToMilliseconds(\DateTime $dateTime)
{
$secs = $dateTime->getTimestamp(); // Gets the seconds
$millisecs = $secs*1000; // Converted to milliseconds
$millisecs += $dateTime->format("u")/1000; // Microseconds converted to seconds
return $millisecs;
}
It requires however that your DateTime object contains the microseconds (u in the format):
$date_str = "20:46:00.588";
$date = DateTime::createFromFormat("H:i:s.u", $date_str);
This is working only since PHP 5.2 hence the microseconds support to DateTime has been added then.
With this function, your code would become the following :
$date_str = "1990-08-07 20:46:00.588";
$date1 = DateTime::createFromFormat("Y-m-d H:i:s.u", $date_str);
$msNow = (int)microtime(true)*1000;
echo $msNow - dateTimeToMilliseconds($date1);
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the 'u' format string.
<?php
// Instantiate a DateTime with microseconds.
$d = new DateTime('2011-01-01T15:03:01.012345Z');
// Output the microseconds.
echo $d->format('u'); // 012345
// Output the date with microseconds.
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345
// Unix Format
echo "<br>d2: ". $d->format('U.u');
function get_data_unix_ms($data){
$d = new DateTime($data);
$new_data = $d->format('U.u');
return $new_data;
}
function get_date_diff_ms($date1, $date2)
{
$d1 = new DateTime($date1);
$new_d1 = $d1->format('U.u');
$d2 = new DateTime($date2);
$new_d2 = $d2->format('U.u');
$diff = abs($new_d1 - $new_d2);
return $diff;
}
https://www.php.net/manual/en/class.datetime.php
Here's a function to do that + tests.
https://gist.github.com/vudaltsov/0bb623b9e2817d6ce359eb88cfbf229d
DateTime dates are only stored as whole seconds. If you still need the number of milliseconds between two DateTime dates, then you can use getTimestamp() to get each time in seconds (then get the difference and turn it into milliseconds):
$seconds_diff = $date2.getTimestamp() - $date.getTimestamp()
$milliseconds_diff = $seconds_diff * 1000

Difference between php timestamp? Or mysql timestamp?

I have two timestamps recorded on a mysql table using php. How can I calculate the difference between these timestamps in hours using php or mysql?
If you actual hours (3600 seconds), it's just a matter of subtracting the timestamps and dividing by 3600:
$hours = ($timestamp2 - $timestamp1)/3600;
$hours = floor($hours); // to round down.
or similar in SQL.
If you want the "logical hours":
$tz = new DateTimezone("Europe/Lisbon"); //replace with actual timezone
$d2 = new DateTime("#$timestamp2");
$d2->setTimezone($tz);
$d1 = new DateTime("#$timestamp1");
$d1->setTimezone($tz);
$hours = $d2->diff($d1)->h;
This makes difference in case there has been a DST change between the two times. Example:
<?php
$ltz = new DateTimezone("Europe/Lisbon");
date_default_timezone_set("Europe/Lisbon");
$ts2 = strtotime("31-Oct-2010 02:30:00");
$ts1 = strtotime("31-Oct-2010 00:30:00");
$d2 = new DateTime("#$ts2");
$d2->setTimezone($ltz);
$d1 = new DateTime("#$ts1");
$d1->setTimezone($ltz);
var_dump(floor($ts2-$ts1)/3600);
var_dump($d2->diff($d1)->h);
gives:
float(3)
int(2)
in php you can just use regular math and then use the date() function to create the datetime represented in hours
Done in PHP, see this: http://php.about.com/od/advancedphp/qt/math_time_php.htm

Categories