calculate difference betwen two datetime in php - php

I have 2 datetime , and I wanna to calculate difference in minutes :
$date_reservation=strtotime($_POST['date_reservation']);;
$dt = new DateTime();
$date_annulation = strtotime($dt->format('Y-m-d H:i:s'));
$attente = (round(abs($date_annulation - $date_reservation)/60)%60);
It only take the difference between minute without hours .
I've tried this function ( from php documentation )
$interval = $date_annulation->diff($date_reservation);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d');
But it dosn't work (error 500)

Your problem is that $date_annulation is not a DateTime object. Keep it simple using strtotime
<?php
$date_reservation = strtotime($_POST['date_reservation']);
$date_annulation = strtotime('now');
$diff_minutes = ($date_annulation - $date_reservation)/60;
echo $diff_minutes;

A response of 500 Internal Server Error means there is a problem in your PHP code. Check the server log files (Apache's error_log, PHP's php_errors.log) to find out the exact place (file and line) and the cause.
In the meantime, the code you copied from the documentation doesn't work because you tried to call a method of the DateTime class on a number (the value returned by strtotime(). It doesn't work this way.
It does work, however, if you use DateTime (and related) objects:
$date_reservation = new DateTime($_POST['date_reservation']);
$date_annulation = new DateTime('now');
$interval = $date_annulation->diff($date_reservation);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d');

If you are aware of the possible inaccuracies using this approach, you can just compare the Unix timestamps:
$date_reservation = strtotime('2016-05-20 13:30');
$date_annulation = strtotime('now');
$diff_minutes = round(abs($date_annulation - $date_reservation)/60, 0);
The only problem in your code is, that you mod 60 your minutes (%60). This of course gives you only the minutes above full hours.
Please note that strtotime interprets the datetime string using the time zone set on the machine running this code. You can set in your code using date_default_timezone_set().
See an example on ideone.com.

i give you code of time difference
<?php
//$datetime1=strtotime('Y-m-d','time to which difference obtained');
$current_time =strtotime(date("Y-m-d H:i:s"));
//$checkTimeEnd = strtotime('time to which difference obtained');
$checkTimeStart = strtotime('time to which difference obtained');
//echo $current_time;
$all = round((($current_time - $checkTimeStart) / 60),2);
//echo floor($all/(60*60*24));
$test = round($all/60,2);
$d = floor ($all / 1440);
$h = floor (($all - $d * 1440) / 60);
$m = $all - ($d * 1440) - ($h * 60);
?>
print $d for date $h for hours $m for minutes

Related

PHP time difference not working for 24 hours

I am trying to calculate the difference in time between two times using this:
round(abs(strtotime("17:30") - strtotime("18:30")) / 60,2);
= '1'
which works fine, but as soon as i make it over 2 days its not calculating correctly
round(abs(strtotime("17:30") - strtotime("02:00")) / 60,2);
= '15.5' this should be '8.5'
For more accurate and correct results you can use ->diff() function. As an example:
<?php
$val1 = '2014-03-18 10:34:09.939';
$val2 = '2014-03-14 10:34:09.940';
$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Output:
-4 days
strtotime returns an timestamp. Currently your calculation is only partly correct, because you ignore negative values. In case of negative values (that should be the case, if the second time is on the next day), you should add 86400 (24*60*60 - the seconds of a day).
$start = strtotime("17:30");
$end = strtotime("02:00");
$diff = $end - $start;
// end date is on the next day
if ($diff < 0) {
$diff += 86400;
}
$hours = $diff / 3600;
echo round($hours, 2);
You can do the math yourself by converting dates into unixtime:
strtotime('2017-12-29 02:00')-strtotime('2017-12-28 17:30')
This will return the difference in seconds, so if I want to print the value in hours, I have to divide by 60 twice:
php > print((strtotime('2017-12-29 02:00')-strtotime('2017-12-28 17:30'))/60/60);
8.5

Calculating percent of time remaining from two dates

So far im trying to get the percentage of time remaining between two dates so i can use a progress bar..
I have the following code i'm passing in two dates and doing the sum but i am getting an error. i'm not sure if this error is because of the date format if so i can change it.
<?
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
$current = '2015-11-03 16:12:15';
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>
I am getting the following error.
Warning: Division by zero
strtotime will take a date string and turn it into unix standard time as seconds.
<?
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>
I would recommend using the DateTime object over strtotime. DateTime allows you to specify the format that creates the timestamp, instead of relying on strtotime to magically figure it out. This makes it far more reliable.
For example:
<?php
$start = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 14:05:15');
$end = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 18:05:15');
$current = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 16:12:15');
$completed = (($current->getTimestamp() - $start->getTimestamp()) / ($end->getTimestamp() - $start->getTimestamp())) * 100;
echo $completed;
?>
Note: DateTime objects were introduced in PHP 5.3. Any older versions will not have DateTime. (and quite honestly, should be updated for many reasons)
You're using strings (basically, plain text)... So you can't calculate anything.
You should use timestamps for that (miliseconds since start of 1970)
http://php.net/manual/fr/function.strtotime.php
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');
Those are strings. You can't subtract strings and expect things to work. What's happening is this:
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
Since you're doing -, PHP converts those strings to integers:
$new_start = (int)$start; // 2015
$new_end = (int)$end; // 2015
$new_end - $new_start -> 0
YOu need to strtotime() those values back into a unix timestamp, and then you CAN subtract those values, and get a difference in seconds.

php where is my percentage of the day being calculated wrong?

I been trying to fix this php percentage calculator of the day...basically right now here is about 230pm and I am getting 73% of the day completed....it should be more like 60% of the day. Here is the code:
$now = time();
$today = strtotime(date("m/d/Y"));
$seconds = $now - $today;
$day = 24*60*60;
$percent = $seconds / $day*100;
I attempted to write my own version but I am getting 100% of the day...Here is the code:
$todaysTime = time();
$todaysStart = time()-86400;
$todayCalc = $todaysTime - $todaysStart;
$dayPhpOne = 24*60*60;
$percentDay = $todayCalc / $dayPhpOne*100;
It is done in php where am I messing up my code?
Try this:
$percentDay = time() % 86400 / 864;
Edit
From the comments I take, that I didn't elaborate on time zones. Let me make clear, that this is meant to be UTC day percent.
This solution does respect timezone and other time-related complexities:
$d = new DateTime();
$h = $d->format('H');
$m = $d->format('i');
$s = $d->format('s');
$currentSecond = $h * 3600 + $m * 60 + $s;
$midnight = new DateTime($d->format('Y-m-d'), $d->getTimezone());
$tomorrow = clone $midnight;
$tomorrow = $tomorrow->add(new DateInterval('P1D'));
$secondsToday = $tomorrow->getTimestamp() - $midnight->getTimestamp();
$percent = $currentSecond / $secondsToday * 100;
var_dump($percent);
If necessary - it's possible to specify a particular timezone to be used as a second DateTime constructor argument.

Date is not formatting time correctly PHP

Hello I try to take the difference between two dates and display it.
My problem is that the time difference I get is not the correct one.
This is my code:
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
echo date('H:i', $diffTime);
The result I get is:
02:05
The currect time should be this:
00:05
My guess that the date somehow takes timezone or something like this but Im not sure.
Thanks.
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give
$end_date = new DateTime('00:00:00'); *a wrong answer
*****************************************/
$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');
$dd = date_diff($end_date, $start_date);
//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
So what you're actually doing here is generating two UNIX timestamps (numbers) and then subtracting them. then you're passing the resulting number as if it were still a timestamp to date().
essentially $diffTime is the number of seconds between your two times. you could divide by 60 to get minutes, and so on and so forth, but PHPs DateTime objects are much better.
From the PHP docs:
http://pl1.php.net/strtotime
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
try this
<?php
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
echo round(abs($time1 - $time2) / 60,2). " minute"
?>
Below is the solution of date time in years,days.hours,minutes and seconds.
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
$y = ($diffTime/(60*60*24*365));
$d = ($diffTime/(60*60*24))%365;
$h = ($diffTime/(60*60))%24;
$m = ($diffTime/60)%60;
$s = ($diffTime)%60;
echo "Minutes - " .$m;
echo "<br/>";

Get interval seconds between two datetime in PHP?

2009-10-05 18:11:08
2009-10-05 18:07:13
This should generate 235,how to do it ?
With DateTime objects, you can do it like this:
$date = new DateTime( '2009-10-05 18:07:13' );
$date2 = new DateTime( '2009-10-05 18:11:08' );
$diffInSeconds = $date2->getTimestamp() - $date->getTimestamp();
You can use strtotime() to do that:
$diff = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')
A similar approach is possible with DateTime objects, e.g.
$date = new DateTime( '2009-10-05 18:07:13' );
$date2 = new DateTime( '2009-10-05 18:11:08' );
$diff = $date2->getTimestamp() - $date->getTimestamp();
PHP Date Time reference is helpful for things like this: PHP Date Time Functions
strtotime() is probably the best way.
$seconds = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')
For those worrying about the limitations of using timestamps (i.e. using dates before 1970 and beyond 2038), you can simply calculate the difference in seconds like so:
$start = new DateTime('2009-10-05 18:11:08');
$end = new DateTime('2009-10-05 18:07:13');
$diff = $end->diff($start);
$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->h * 60 * 60;
$minsInSecs = $diff->i * 60;
$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->s;
echo $seconds; // output: 235
Wrote a blog post for those interested in reading more.
Because of unix epoch limitations, you could have problems compairing dates before 1970 and after 2038. I choose to loose precision (=don't look at the single second) but avoid to pass trough unix epoch conversions (getTimestamp). It depends on what you are doing to do...
In my case, using 365 instead (12*30) and "30" as mean month lenght, reduced the error in an usable output.
function DateIntervalToSec($start,$end){ // as datetime object returns difference in seconds
$diff = $end->diff($start);
$diff_sec = $diff->format('%r').( // prepend the sign - if negative, change it to R if you want the +, too
($diff->s)+ // seconds (no errors)
(60*($diff->i))+ // minutes (no errors)
(60*60*($diff->h))+ // hours (no errors)
(24*60*60*($diff->d))+ // days (no errors)
(30*24*60*60*($diff->m))+ // months (???)
(365*24*60*60*($diff->y)) // years (???)
);
return $diff_sec;
}
Note that the error could be 0, if "mean" quantities are intended for diff. The PHP docs don't speaks about this...
In a bad case, error could be:
0 seconds if diff is applied to time gaps < 1 month
0 to 3 days if diff is applied to time gaps > 1 month
0 to 14 days if diff is applied to time gaps > 1 year
I prefer to suppose that somebody decided to consider "m" as 30 days and "y" as 365, charging "d" with the difference when "diff" walk trough non-30-days months...
If somebody knows something more about this and can provide official documentation, is welcome!
strtotime("2009-10-05 18:11:08") - strtotime("2009-10-05 18:07:13")
The solution proposed by #designcise is wrong when "end date" is before "start date".
Here is the corrected calculation
$diff = $start->diff($end);
$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->format('%r%h') * 60 * 60;
$minsInSecs = $diff->format('%r%i') * 60;
$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->format('%r%s');
A simple and exact solution (exemplifying Nilz11's comment):
$hiDate = new DateTime("2310-05-22 08:33:26");
$loDate = new DateTime("1910-11-03 13:00:01");
$diff = $hiDate->diff($loDate);
$secs = ((($diff->format("%a") * 24) + $diff->format("%H")) * 60 +
$diff->format("%i")) * 60 + $diff->format("%s");

Categories