php: datetime() difference between 2 datetime with 2 variables - php

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

Related

Comparing two dates results 0

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*/;
}

date('H:i',$ans) returns wrong value

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

How can i get difference between two time stamp

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

User friendly date formatting [duplicate]

This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
Closed 9 years ago.
I am trying to display user friendly date formatting such as "1 hour and 15 minutes", "4 days and 8 hours" to the user. However my script is displaying 0 hours as 23 for some reason.
$date = '2014-01-15 15:00' # PAST DATE
$now = Date("Y-m-d H:m:s");
$seconds = strtotime($now) - strtotime($date);
$days = floor($seconds / 86400);
$hours = floor(($seconds - ($days * 86400)) / 3600);
$minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60);
$seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes*60)));
if($days > 0)
{
if($days == 1)
{
return $days . ' dag ' . $hours . ' timmar';
} else {
return $days . ' dagar ' . $hours . ' timmar';
}
}
if(($hours < 24) AND ($hours > 0))
{
return $hours . ' timmar';
}
if($minutes < 60)
{
return $minutes . ' minuter';
}
Can anyone see what is causing this? Am I doing it the correct way? Note that $date is user supplied in the past.
There are much easier ways to do this:
$past = new DateTime('2014-01-15 15:00');
$now = new DateTime();
$interval = $now->diff($past);
echo $interval->format('%y years, %m months, %d days,
%h hours, %i minutes, %S seconds');
An obvious improvement is to use now show periods of time that have zero values (i.e. 0 days):
$elapsed = $interval->format('%y years, %m months, %d days,
%h hours, %i minutes');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,',
' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ',
' 1 hours, ', ' 1 minutes'), array('1 year, ',
'1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'),
$elapsed);
Use something like this:
$date = '2014-01-15 15:00' # PAST DATE
now = Date("Y-m-d H:m:s");
$t = strtotime($now) - strtotime($date);
$time = date('g:iA M dS', $t );
$diff = time() - $t;
if ( $diff < 60 )
{
return "a few seconds ago";
}
elseif ( $diff < 3600 )
{
return "about ".( int ) ($diff/60) ." mins ago";
}
elseif ( $diff < 86400 )
{
if ( ( int ) ($diff/3600) == 1 )
{
return "about an hour ago";
}
else
{
return "about ".( int ) ($diff/3600) ." hours ago";
}
}
else if( $diff < 172800 )
{
return "about a day ago";
}
elseif ( $diff > 172800 )
{
return "$time";
}

How long time it is left? php + date

//Example data
$current_time = 1318075950;
$unbanned_time = $current_time + strtotime('+1 minute');
if ($unbanned_time > $current_time) {
$th1is = date('Y-m-d H:i:s', $unbanned_time) - date('Y-m-d H:i:s', $current_time);
echo date('Y-m-d H:i:s', $th1is);
I am trying to output how long time it is until the user is unbanned... year months, days, hours, minutes and seconds... But this is giving me some weird results..
You should check manual on how to work with date/time functions.
First of all, instead of
$current_time + strtotime('+1 minute')
use
strtotime('+1 minute', $current_time);
(see manual on strtotime).
Secondly, date function returns a string. Subtracting two strings is not really useful in most cases.
if ($unbanned_time > $current_time) {
$th1is = $unbanned_time - $current_time;
echo $th1is/3600 . ' hours';
}
This will output the remaining time in hours but there are many functions available that will produce better formatting (or you can code one for yourself).
I would recommend to use DateTime
$DateTime = new DateTime();
$unbanned_DateTime = new DateTime();
$unbanned_DateTime = $unbanned_DateTime->modify('+1 minute');
if ( $unbanned_DateTime > $DateTime ) {
$interval = $DateTime->diff($unbanned_DateTime);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d');
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
$seconds = $interval->format('%s');
}
Instead of using every single value as variable you can use ->format() for one output. As you like.
Remember DateTime->format() needs a timezone setting up in your php.ini or with
date_default_timezone_set('....');
date() returns a string, substracting two strings makes no sense here. You can use basic maths to calculate the remaining time:
<?php
$current_time = time();
$unbanned_time = /* whatever */;
$seconds_diff = $unbanned_time - $current_time();
echo "You're unbanned at " . date("Y-m-d H:i:s", $unbanned_time) . " which is over ";
if ($seconds_diff <= 120) {
echo "$seconds_diff seconds";
} else if ($seconds_diff <= 7200) {
echo floor($seconds_diff / 60) . " minutes";
} else if ($seconds_diff <= 7200 * 24) {
echo floor($seconds_diff / 3600) . " hours";
} else {
echo floor($seconds_diff / 3600 / 24) . " days";
}
?>

Categories