Comparing two dates results 0 - php

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

Related

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

Php's new DateTime() is not working on my new server

I am trying to calculate the time interval between two Dates. So here is my code
$start_date = new DateTime("$date1");
$end_date = new DateTime("$date2");
$interval = $start_date->diff($end_date);
$days = $interval->d;
$months = $interval->m;
$years = $interval->y;
$hours = $interval->h;
$mins = $interval->i;
$secs = $interval->s;
when i try to echo the result it returns an empty result.
This same code worked on my development server and localhost, As soon as i changed to another server it stoped responding.
I checked php.ini for timezone setting, it was good.
I will be thank full for your help
Check your php.ini files inside /etc/php5/apache2/ and /etc/php5/cli/ folders. Both files must have declared the default time zone eg. date.timezone = "America/New_York"
Other way you can have it to work is declaring it inside your code before creating the DateTime object
date_default_timezone_set('America/New_York');
$start_date = new DateTime("$date1");
$end_date = new DateTime("$date2");
$interval = $start_date->diff($end_date);
$days = $interval->d;
$months = $interval->m;
$years = $interval->y;
$hours = $interval->h;
$mins = $interval->i;
$secs = $interval->s;
NOTE: I suggest that you store everything in timestamp in your database rather than in date. And in your display logic, convert it to date, or find how old it is, etc. Read this on Datetime vs timestamp Should I use field 'datetime' or 'timestamp'?
Below,find two functions to find time difference between two timestamps as well as get the age of an old timestamp compared to now.
<?php
echo whatAge(#SOME TIMESTAMP HERE#)
echo getDiff(#TIMESTAMP1, TIMESTAMP2#)
?>
This gives you day hour minute second. Modify the secondsToTime function below for something else.
Use the functions below...
function whatAge($old_time){
$current_time = getdate(time())[0];
$time_diff = $current_time-$old_time;
return secondsToTime($time_diff,'string');
}
function getDiff($time1, $time2){
$time_diff = $time1-$time2;
return secondsToTime($time_diff,'string');
}
function secondsToTime($inputSeconds, $return='array') {
/** https://stackoverflow.com/questions/8273804/convert-seconds-into-days-hours-minutes-and-seconds */
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($inputSeconds / $secondsInADay);
// extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// return the final array
$obj = array(
'd' => (int) $days,
'h' => (int) $hours,
'm' => (int) $minutes,
's' => (int) $seconds,
);
$str = function($d,$h,$m,$s){
if($d>0){
return "$d d, $h h $m m";
}else{
return "$h h $m m";
}
};
switch ($return){
case 'array' : return $obj; break;
case 'string' : return $str($obj['d'],$obj['h'],$obj['m'],$obj['s']); break;
}
}
Simple Way
Try this:
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
read more [php DateTime::diff manual][1]

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

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