I have to calculate a time difference in php script. There are in time and out time values. I wrote following code to get the difference. But it always returns correct answer + 1 value.
$inTime = '08:30:00';
$outTime = '17:48:00';
$difference = date('H:i',((strtotime($outTime) - strtotime($inTime))));
echo $difference;
The out put is printed as 10:18. But the output should be 09:18. I use Codeigniter framwork. I run this code with online php tester (http://phptester.net/) and it returns the correct value.
check out this method...
<?php
$time1 = new DateTime('08:30:00');
$time2 = new DateTime('17:48:00');
$interval = $time2->diff($time1);
echo "Time Difference : ".$interval->format('%H hours %i minutes %s seconds');
?>
This will output :
Time Difference : 09 hours 18 minutes 0 seconds
function datediff( $date1, $date2 )
{
$diff = abs( strtotime( $date1 ) - strtotime( $date2 ) );
return sprintf
(
"%d Days, %d Hours, %d Mins, %d Seconds",
intval( $diff / 86400 ),
intval( ( $diff % 86400 ) / 3600),
intval( ( $diff / 60 ) % 60 ),
intval( $diff % 60 )
);
}
$inTime = '08:30:00';
$outTime = '17:48:00';
print datediff( $inTime, $outTime ) . "\n";
Online Demo : Click Here
For only Minutes:
function datediff( $date1, $date2 )
{
$diff = abs( strtotime( $date1 ) - strtotime( $date2 ) );
return sprintf
(
"%d Mins",
intval(((( $diff % 86400 ) / 3600) * 60))
);
}
$inTime = '08:30:00';
$outTime = '17:48:00';
print datediff( $inTime, $outTime ) . "\n";
Output
558 Mins
Online Demo: Click Here
There are lots of ways you can do this, personally I would use PHP's built in time difference functions.
$inTime = date_create('08:30:0');
$outTime = date_create('17:48:00');
$difference = date_diff($inTime, $outTime);
echo $difference->format('%H:%I:%S');
outputs:
09:18:00
example
Related
so i'm currently making a small php application and I need to compare two dates to get the number of days between them.
I sadly can't use datediff() since the php version is 5.2.
I've search how to do and I found a lot of answers but I always have the same problem. When I make the difference between my dates, I always got 0 as a result.
function date_diff($dateFrom, $dateTo) {
echo $dateFrom->format('d-m-Y') . " : " . $dateTo->format('d-m-Y') . '<br/>';
$diff = abs($dateTo-$dateFrom);
return sprintf
(
"%d Days, %d Hours, %d Mins, %d Seconds",
intval( $diff / 86400 ),
intval( ( $diff % 86400 ) / 3600),
intval( ( $diff / 60 ) % 60 ),
intval( $diff % 60 )
);
}
I currently use this function and the parameters are here :
while ($donnees = mysqli_fetch_array($res))
$date = new DateTime($donnees['Date']);
$date = date_create($date->format("Y-m-d"));
$today = new DateTime();
echo $utilDate->date_diff($date, $today);
My $date and $today variables are not empty, so I don't understand why this code doesn't work.
Does anyone have an idea?
I think $dateTo and $dateFrom are objects and you are doing a substraction on them in $diff = abs($dateTo-$dateFrom);
Try $diff = abs($dateTo->getTimestamp()-$dateFrom->getTimestamp());
You want to use the diff operator:
function date_diff($dateFrom, $dateTo) {
echo $dateFrom->format('d-m-Y') . " : " . $dateTo->format('d-m-Y') . '<br/>';
$diff = $dateNow->diff($dateTo);
$day = $diff->format('%d');
$hour = $diff->format('%h');
$min = $diff->format('%i');
$seconds = $diff->format('%s');
return /*string involving above formats*/;
}
I am working on a project, in that i need to check the time difference, between two times, and also i need to compare the time difference. If the time difference is >= 10 minutes, i need to execute some queries.. Please help, i am working on that from last 2 days.
$db=new Database($dbserver,$dbuser,$dbpassword,$dbname);
$db->connect();
$result=$db->query("SELECT reservedBy, bikeNum FROM bikes WHERE reserveBy
IS NOT NULL");
while ($row=$result->fetch_assoc()) {
$userid=$row["reservedBy"];
$bike=$row["bikeNum"];
$result=$db->query("SELECT time FROM history WHERE userId=$userid AND bikeNum=$bike AND action='RESERVE' ORDER BY time DESC LIMIT 1");
$row=$result->fetch_assoc();
$time=$row["time"];
echo $time. "<br>";
$date = date('Y-m-d H:i:s ', time());
echo $date;
$timediff=date_diff($date$time);
if($timediff>10) {
$result=$db->query("UPDATE bikes SET reservedBy=NULL WHERE
bikeNum=$bike");
}
}
try this
function datediff( $date1, $date2 )
{
$diff = abs( strtotime( $date1 ) - strtotime( $date2 ) );
return sprintf
(
"%d Days, %d Hours, %d Mins, %d Seconds",
intval( $diff / 86400 ),
intval( ( $diff % 86400 ) / 3600),
intval( ( $diff / 60 ) % 60 ),
intval( $diff % 60 )
);
}
print datediff( "18th February 2013", "now" ) . "\n";
OR this:
$start_date = new DateTime("2012-02-10 11:26:00");
$end_date = new DateTime("2012-04-25 01:50:00");
$interval = $start_date->diff($end_date);
echo "Result " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
I have in my database 4 columns which are:
Date_in | Time_in | Date_out | Time_out
Date_in and Time_in belong together (e.g., 2013-02-18 13:00:00) and date_out goes with Time_out. I would like to find out the difference between and I have gotten up till:
$start_time = new DateTime("'$list[date_in] "."$list[time_in]'");
$since_start = $start_time->diff(new DateTime("'$list[date_out] "."$list[time_out]'"));
$hours = $since_start->h.' hours';
But it doesn't work. I think my quotes and double quotes are all messed up because the use of " ' . really confuses me..
Thanks in advance for any advice on how I can fix my code!
[EDIT]
Thanks everyone for all your detailed help! I just realised that the server doesn't support php 5.3 and I can't use datetime().
So my solution was:
$start_time = strtotime("$list[date_in] " . "$list[time_in]");
$end_time = strtotime("$list[date_out] " . "$list[time_out]");
$hours = abs(($end_time - $start_time)/3600);
Try this,
function datediff( $date1, $date2 )
{
$diff = abs( strtotime( $date1 ) - strtotime( $date2 ) );
return sprintf
(
"%d Days, %d Hours, %d Mins, %d Seconds",
intval( $diff / 86400 ),
intval( ( $diff % 86400 ) / 3600),
intval( ( $diff / 60 ) % 60 ),
intval( $diff % 60 )
);
}
print datediff( "18th February 2013", "now" ) . "\n";
OR
You can use DateTime::diff
$start_date = new DateTime("2012-02-10 11:26:00");
$end_date = new DateTime("2012-04-25 01:50:00");
$interval = $start_date->diff($end_date);
echo "Result " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
EDIT:
Checkout links,
How to calculate the difference between two dates using PHP?
Php Date Time – 7 Methods to Calculate the Difference between 2 dates.
may help you.
You don't need quotes if you want to evaluate the variables content.
In this case, you only need them to create a separation between date and time:
$start_time = new DateTime($list['date_in']." ".$list['time_in']);
$since_start = $start_time->diff(new DateTime($list['date_out']." ".$list['time_out']));
I am using the dot . in order to concatenate variables with an string, in this case the string is a white space.
You can read more about concatenation in the documentation.
$start_time = new DateTime("$list[date_in] " . "$list[time_in]");
$since_start = $start_time->diff(new DateTime("$list[date_out] " . "$list[time_out]"));
OR
$start_time = new DateTime("{$list['date_in']} {$list['time_in']}");
$since_start = $start_time->diff(new DateTime("{$list['date_out']} {$list['time_out']}"));
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Set default diff to 0
$diffs[$interval] = 0;
// Create temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
$time1 = $ttime;
$diffs[$interval]++;
// Create new temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
}
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
// Set start & end time
$start_time = "2013-02-18 13:00:00";
$end_time = "2013-02-16 10:00:00";
// Run and print diff
echo dateDiff($start_time, $end_time, 6);
The last argument is the precision.
$diff = abs( strtotime( '2014-04-25 16:00:00' ) - strtotime( '2014-04-27 18:02:00' ) );
if(sprintf("%d",intval( $diff / 86400 )) != '0'){
if(sprintf("%d",intval( $diff / 86400 )) == '1'){
echo sprintf("%02d day ", intval( $diff / 86400 ));
}else{
echo sprintf("%02d days ", intval( $diff / 86400 ));
}
}
if(intval( ( $diff % 86400 ) / 3600) != '0'){
if(intval( ( $diff % 86400 ) / 3600) == '1'){
echo sprintf("%02d hour ", intval( ( $diff % 86400 ) / 3600));
}else{
echo sprintf("%02d hours ", intval( ( $diff % 86400 ) / 3600));
}
}
if(intval( ( $diff / 60 ) % 60 ) != '0'){
if(intval( ( $diff / 60 ) % 60 ) == '1'){
echo sprintf("%02d min", intval( ( $diff / 60 ) % 60 ));
}else{
echo sprintf("%02d mins", intval( ( $diff / 60 ) % 60 ));
}
}
how can I find the next closest hour in php
so for example if current time is 4:15 the next hour will be 5, etc
$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
echo $date->format( 'H:i:s' );
gives me the time from the string and I want to expand on that and get the next closest hour
$nextHour = (intval($date->format('H'))+1) % 24;
echo $nextHour; // 5
Here we go:
<?php
echo date("H:00",strtotime($date. " + 1hour "));
?>
Can you just take pieces (hours, minutes, seconds) and get the next hour?
$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
echo $date->format( 'H:i:s' );
echo "\n";
$nexthour = ($date->format('H') + ($date->format('i') > 0 || $date->format('s') > 0 ? 1 : 0)) % 24;
echo "$nexthour:00:00";
Supply any eligible date() to:
function roundToNextHour($dateString) {
$date = new DateTime($dateString);
$minutes = $date->format('i');
if ($minutes > 0) {
$date->modify("+1 hour");
$date->modify('-'.$minutes.' minutes');
}
return $date;
}
<?php
$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
$date->modify('+1 hour');
echo $date->format('H:i:s').PHP_EOL;
// OR
echo date('H:i:s', strtotime($dateString) + 60 * 60).PHP_EOL;
As I just needed something similar (next full hour) here my solution:
$now = time();
$nextFullHour = date(DATE_ATOM, $now + (3600 - $now % 3600));
By replacing the 3600 e.g. with 60 you get the next full minute...
You can also replace the $now with any other timestamp if you do not need it relative to the current time.
That is my solution:
$dateTime = new \DateTime();
$dateTime->add(new \DateInterval('PT1H'))
->setTime($dateTime->format('H'), '00');
Nobody else used this one so I figured I'd drop it here, simplest one I saw above for an actual timestamp, not just the hour itself.
$now = ''; // empty uses current time, or you can insert a datetime string
$next_hour = date( 'Y-m-d H:00:00', strtotime( $now . ' +1 hour' ) );
try it for current time, if you need put second argument to date function
<?php echo date('H')+1; ?>
very nice stuff
One more:
$current_datetime = new DateTimeImmutable();
$next_full_hour_datetime = $current_datetime
->modify(
sprintf(
'+%d seconds',
3600 - ($current_datetime->getTimestamp() % 3600)
)
);
A little late to this party, but here's a more flexible function to round up a dateTime object by any interval in minutes. You pass in your dateTime object and a rounding interval in minutes, so for an hour you'd just pass in 60, etc.
public function round_up_time( $datetime, $rounding_interval ) {
// get total minutes from the start of the day
$minutes = ( intval( $datetime->format( 'H' ) ) * 60 ) + ( intval( $datetime->format( 'i' ) ) );
// round up the minutes based on the interval we are rounding to
$rounded_minutes = ( intval( $minutes / $rounding_interval ) + 1 ) * $rounding_interval;
// reset our dateTime to the very start of the day
$datetime->setTime( 0, 0 );
// then increase the dateTime by the rounded minutes value
$datetime->modify( '+ ' . $rounded_minutes . ' minutes' );
}
To get the next closest full hour in DateTime:
$date = new DateTime('+1 hour'); //set the next hour
$date->setTime($date->format('H'), '00', '00'); //keep the next hour, set minutes to 00 and seconds to 00
I have a DATETIME for an entry in my database that is upcoming. I want to know the difference in time between the the DATETIME and the current date/time in Days, Hours, Minutes, and Seconds. I thought I might be able to use the date function to do this, but perhaps I am wrong.
This was my approach:
$now = mktime(0, 0, 0, date("m"), date("d"), date("y"));
$entry_datetime = strtotime($row['end_auction']);
$difference = date("G, i, s",($entry_datetime - $now));
echo $difference;
The result i received is
13, 20, 00
but that doesn't make any sense since the DATETIME in $row['end_auction'] is November 28th and today is November 19th, so much more than 13 hours apart.
How do I find the difference between the two values and how do I format it to appear as:
9 days, 10 hours, 32 minutes, and 20
seconds
Thank you in advance!
function datediff( $date1, $date2 )
{
$diff = abs( strtotime( $date1 ) - strtotime( $date2 ) );
return sprintf
(
"%d Days, %d Hours, %d Mins, %d Seconds",
intval( $diff / 86400 ),
intval( ( $diff % 86400 ) / 3600),
intval( ( $diff / 60 ) % 60 ),
intval( $diff % 60 )
);
}
print datediff( "24th November 2009", "now" ) . "\n";
You could use UNIX_TIMESTAMP() in mysql to get the timestamp and then operate them with php's date functions