Comparing datetimes in php - php

I am comparing a date with a datetime and I get the result I expect however I also am wondering if there is a better way to display my output and I have a query on my current output also.
Here is a snippet of my current code:
<?php
$todayDate = date('Y-m-d');
$seconds = strtotime($todayDate) - strtotime($dueDate);
$hours = $seconds / 60 / 60;
echo number_format($hours, 2);
?>
in my case $dueDate in my database here is 2017-06-26 09:11:28 so the output is displaying as -57.19. My question, is there is a clean way to strip the - and also add h after the hours and m after the minutes so the output looks like this?
57h 19m
UPDATE
So After tinkering around I have managed to do this:
substr($dateFormat,0,3).'h '.substr($dateFormat,4).'m';
The output now is -57h 19m
I still have this negative character, im not sure if that is actually correct I cannot seem to work it out because the date in my database is a day ahead but it shows a negative value...

Using the DateTime class makes it very simple
$dueDate = '2017-06-26 09:11:28';
$due = DateTime::createFromFormat('Y-m-d H:i:s', $dueDate);
$today = new DateTime();
$diff = $today->diff($due);
echo $diff->format('%hh %im');
Result:
11h 37m
But as you asked about timezones, here is how to add those in as well. And also as you orignial date was in fact some days distant I added a more accurate difference output
$dueDate = '2017-06-25 00:00:00';
$due = DateTime::createFromFormat('Y-m-d H:i:s', $dueDate, new DateTimeZone('Europe/London'));
$today = new DateTime('now', new DateTimeZone('Europe/London'));
$diff = $today->diff($due);
echo $diff->format('%R %hh %im').PHP_EOL;
if ( $diff->invert ) {
echo $diff->format('Overdue by %dd %hh %im');
} else {
echo $diff->format('You have %dd %hh %im till overdue');
}
Results
+ 1h 6m
You have 0d 1h 6m till overdue

You need to keep date integer
$time = time();
after
you can use this every where and evert way
For example
$date1 = time();
$date2 = time();
$comparingdate = $date2 - $date1;
$myFormat = date("T-m-d h:i:s",$comparingdate); // Show how you want

use floor and round functions to get the minutes and hours after convert the date to positive sign using abs function
<?php
$todayDate = date('Y-m-d');
$dueDate = "2017-06-26 09:11:28";
$seconds =abs(strtotime($todayDate) - strtotime($dueDate));
$hours =floor($seconds / 60 / 60);
$minutes= round($seconds / 60 / 60 - $hours,2)*100;
echo "<br>";
echo $hours. " H :";
echo $minutes. " M ";
?>

Related

PHP subtract unknown time from datetime

So, I'm creating a booking system. When I retrieve this booking from the database, I need to check if the current date and time is closer to the actual booked date and time.
On the admin dashboard, the admins specify how much time earlier the client can make a checkin, let's say for example, 30minutes. But this time can be different. Can be 1hour, 2hours, 10minutes.
When I get the result from the database I get them like this:
$date_schedule = '2021-03-25 15:40:00'; // Can be any date in the future as well;
$time_to_check = '00:30:00'; // Can be '01:05:00', whatever the admins set as time_to_check;
// Expected result
'2021-03-25 15:10:00';
I tried subtracting this but I didn't made it work.. This is what I did.
$current_date = date("Y-m-d H:i:s");
$booking_date = '2021-03-25 15:00:00'; // From database
$time_to_check = '00:30:00'; // From database
$hours = explode(':', $time_to_check);
$data_check = date($booking_date, strtotime('-' . $hours[0] . ' hour -' . $hours[1] . ' minutes'));
But with this, $data_check returns the same value as $booking_date, it's not subtracting the time.
Convert your date to DateTime to make some operations on it :
function changeDate($date, $interval) {
$datetime = new DateTime($date);
$values = explode(':', $interval);
$datetime->modify("-$values[0] hours -$values[1] minutes -$values[2] seconds");
return $datetime->format('Y-m-d H:i:s');
}
$date = changeDate('2021-03-25 15:00:00', '00:30:00');
echo $date; // 2021-03-25 14:30:00
$date = changeDate('2021-03-25 15:00:00', '01:30:00');
echo $date; // 2021-03-25 13:30:00
$date = changeDate('2021-03-25 15:00:00', '02:30:15');
echo $date; // 2021-03-25 12:29:45
You can find documentation here https://www.php.net/manual/en/book.datetime.php
Just convert the timestamp to Unix time, and then subtract 30 minutes in seconds (30 * 60) from the Unix time.
Like this:
$date = '2021-03-25 15:10:00';
$timestamp = strtotime($date);
$timestamp = ($timestamp - (30 * 60));
echo gmdate("Y-m-d H:i:s", $timestamp);
EDIT: If you are in an odd timezone, like me (GMT+0100) add or subtract difference;
$timestamp = (($timestamp - (30 * 60)) + (1 * 60 * 60))

Add fractional hours to a DateTime in php

I have a system which I need to add a certain amount of fractional hours.
I've been searching and this is what I got, by far it's the most accurate method, but still doesn't give me the answer I need
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = array();
$time = explode(".", $hours);
$time [1] += $time [0]*60;
$now->modify("+".$time[1]." hours");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer ->format('Y-m-d H:i:s');
The answer that I want to reach is "2017-11-09 11:00:00" and I receive "2017-10-25 12:22:23" instead
Adding the hours is not correct. When you multiply hours times 60 it will make minutes.
This code should work.
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = explode(".", $hours);
$time[1] += $time[0]*60;
$now->modify("+".$time[1]." minutes");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer->format('Y-m-d H:i:s');
Result is 2017-10-30 09:46:00
You should use DateInterval php class to create an inverval with x seconds from your $hours variable.
Then you just have to use the datetime add interval method to modify your date
Please take a look a this example
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
var_dump($now);
$timeParts = explode(".", $hours);
// Where 23 is a percentage of on hour
$minutes = $timeParts[0] * 60 + round($time[1] * 60 / 100);
// Where 23 is the number of minutes
$minutes = $timeParts[0] * 60 + $time[1];
$interval = new DateInterval(sprintf('PT%dM', $minutes));
$now->add($interval);
echo $now->format('Y-m-d H:i:s');
return $now;
}
Use date_add
date_add($now, date_interval_create_from_date_string($tempo[1]' hours'));
or as object:
$now->add( DateInterval::createFromDateString($tempo[1].' hours'));

Change days to hours with date_diff

$time = Whatever i want
$future_date = new DateTime(date('r',strtotime($time)));
$time_now = time();
$now = new DateTime(date('r', $time_now));
interval = date_diff($future_date, $now);
echo $interval->format('%H:%I');
When i run this... i get an output WITH days, you just cant see them. How can i roll the days into the hours (like to have 35 hours for example)?
This is part of a longer script im writing, im aware there are different ways of doing this....
EDIT
Using the answers below, i've come up with this:
$time = '2013-10-8 11:10:00';
$future_date = new DateTime($time);
$now = new DateTime();
$interval = date_diff($future_date, $now);
$text = $interval->days * 24 + $interval->h . ':' . $interval->i;
I'm trying to output the hours and minutes in this format (00:00), WITH leading zeros. Now out of my depth...
Example how to get difference between dates/timestamps in hours:
$future = new DateTime('#1383609600');
$now = new DateTime;
$diff = $now->diff($future);
echo $diff->days * 24 + $diff->h;
Update: if you wish to format output numbers with leading zeros, you can use sprintf() or str_pad() function. Example of sprintf() use:
echo sprintf('%02d:%02d', $diff->days * 24 + $diff->h, $diff->i);

Setting a time and date and adding to it in PHP

Basically am trying to set a time and a date in PHP then set a time gap which will range between minutes, loop through between a start time and end time echoing something out for each one. Have tried loads of different ways and cant seem to figure a way to set a date and add to it.
This seems the best script I have modified so far:
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
$newendtime = $endtime->format('Y-m-d H:i');
$timedate = new DateTime('2012-01-01 09:00');
while($stamp < $newendtime)
{
$time = new DateTime($timedate);
$time->add(new DateInterval('PT' . $minutes . 'M'));
$timedate = $time->format('Y-m-d H:i');
echo $timedate;
}
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
//modified the start value to get something _before_ the endtime:
$time = new DateTime('2012-01-01 8:00');
$interval = new DateInterval('PT' . $minutes . 'M');
while($time < $endtime){
$time->add($interval);
echo $time->format('Y-m-d H:i');
}
Do everything in seconds, and use php's time(), date(), and mktime functions.
In UNIX Time, dates are stored as the number of seconds since Jan 1, 1970.
You can render UNIX Timestamps with date().
$time = time(); // gets current time
$endtime = mktime(0,0,0, 1, 31, 2012); // set jan 31 # midnight as end time
$interval = 60 * 5; // 300 seconds = 5 minutes
while($time < $endtime){
$time += $interval;
echo date("M jS Y h:i:s a",$time) . "<br>"; // echos time as Jan 17th, 2012 1:04:56 pm
}
date reference:
http://us3.php.net/manual/en/function.date.php (includes superb date format reference too)
mktime reference: http://us2.php.net/mktime
time() only gets the current time, but just for kicks n' giggles: http://us2.php.net/time
And, it's super easy to store in a database!
This function will let you add date to your existing datetime. This will also preserves HH:MM:SS
<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
?>
Usage:
add_date($date,12,0,0);
where $date is your date.

How do I find the hour difference between two dates in PHP?

I have two dates, formated like "Y-m-d H:i:s". I need to compare these two dates and figure out the hour difference.
You can convert them to timestamps and go from there:
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.
You can use DateTime class also -
$d1= new DateTime("06-08-2015 01:33:26pm"); // first date
$d2= new DateTime("06-07-2015 10:33:26am"); // second date
$interval= $d1->diff($d2); // get difference between two dates
echo ($interval->days * 24) + $interval->h; // convert days to hours and add hours from difference
As an addition to accepted answer I would like to remind that \DateTime::diff is available!
$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);
/**
* #var \DateInterval $diff
*/
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise
\DateInterval documentation.
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
You can try this :
$time1 = new DateTime('06:56:58');
$time2 = new DateTime('15:35:00');
$time_diff = $time1->diff($time2);
echo $time_diff->h.' hours';
echo $time_diff->i.' minutes';
echo $time_diff->s.' seconds';
Output:
8 hours 38 minutes 2 seconds
The problem is that using these values the result is 167 and it should be 168:
$date1 = "2014-03-07 05:49:23";
$date2 = "2014-03-14 05:49:23";
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
$date1 = date_create('2016-12-12 09:00:00');
$date2 = date_create('2016-12-12 11:00:00');
$diff = date_diff($date1,$date2);
$hour = $diff->h;
This is because of day time saving.
Daylight Saving Time (United States) 2014 began at 2:00 AM on
Sunday, March 9.
You lose one hour during the period from $date1 = "2014-03-07 05:49:23" to
$date2 = "2014-03-14 05:49:23";
You can try this:
$dayinpass = "2016-09-23 20:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);
You can use strtotime() to parse your strings and do the difference between the two of them.
Resources :
php.net - strtotime()

Categories