Date_Diff not returning desired result - php

I am a bit confused i am using date_diff to get the days difference in -/+ integer I can only get +days even though it should be -days when the 2nd date is higher than 1st date.
$datetime1 = new DateTime("2018-01-09");
$datetime2 = new DateTime("2018-09-08");
$interval = $datetime1->diff($datetime2);
dd($interval->format('%R%a days'));
result
string(9) "+242 days"
it should be -21 days since date1 is behind by date2 .

Check This output will not confuse you it will give correct output small change to your code
// for negative difference output is -31days and date should be in yy-m-d format
$datetime1 = new DateTime("2018-02-01");
$datetime2 = new DateTime("2018-01-01");
$interval = $datetime1->diff($datetime2);
printf($interval->format('%R%a days'));
echo "<br>";
// for positive difference output is +31days and date should be in yy-m-d format
$datetime3 = new DateTime("2018-01-01");
$datetime4 = new DateTime("2018-02-01");
$interval = $datetime3->diff($datetime4);
printf($interval->format('%R%a days'));
//bellow is output i get which is correct

I'm editing my answer because I think there is a typo in your question when you say -21 days and not -241 days.
So, the standard for DateTime is 'Y-m-d'.
The difference between the dates will be calculated like this:
$firstDate = new DateTime('2018-01-10');
$secondDate = new DateTime('2018-01-15');
$firstDate->diff($secondDate);
Which can be translated as:
$secondDate - $firstDate;

Related

How to find the Time Difference between a PM time and AM time?

In my form there are 2 Time Pickers where user can select a from time and to time. It doesn't have a date associated with it. And for a report generating purpose I've to calculate the time difference between them. It works perfectly to if the From and to Time is "06:00 to 10:00" but if the from and to time is "21:00 to 02:00" I get a time difference of 19 hours. Could you please help me to fix this.
For this case "21:00 to 02:00" the time difference should be 5 hours.
This is the Code
$datetime1 = new \DateTime('09:30 PM');
$datetime2 = new \DateTime('02:00 AM');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh');
exit;
The difference becomes negative If $totime is less than $fromtime.
DateInterval->invert == 1 indicates that. This is used with this short solution to correct the result.
$fromtime = '09:30 PM';
$totime = '02:00 AM';
$diff = date_create($fromtime)->diff(date_create($totime));
$hours = $diff->invert ? 24-$diff->h : $diff->h;
echo $hours; //5
Since you have 2 date pickers one for from time and another to time, the former will always be smaller than the latter. Hence when from time is larger than to time it means user has selected to from the next day. If we don't add a date for calculating difference, PHP will assume today's date by default. We can easily fix this by adding a condition to compare the times and prepend the dates accordingly. Below is the updated code.
<?php
$fromtime = '09:30 PM';
$totime = '02:00 AM';
$now = new \DateTime();
$today = $now->format('Y-m-d'); // Store current date
$now->add(new DateInterval('P1D')); // Add one day to current date to get next date
$nextDay = $now->format('Y-m-d'); // Store next date
if($fromtime > $totime) // If from time is bigger than to time, it means to is a next day
{
$fromdatetime = "$today $fromtime";
$todatetime = "$nextDay $totime";
}
else
{
$fromdatetime = "$today $fromtime";
$todatetime = "$today $totime";
}
$datetime1 = new \DateTime($fromdatetime);
$datetime2 = new \DateTime($todatetime);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh');
?>

Cannot calculate the time difference using PHP

I need to calculate the datetime difference in minutes using PHP. I am explaining my code below .
$date='10-03-2018 03:44 PM';
$endTime = strtotime($date);
$currentDate=date("d-m-Y h:i A");//10-03-2018 03:53 PM
$currentTime = strtotime($currentDate);
echo (round(abs($currentTime - $endTime) / 60,2));//25344617
Here I need to calculate the difference in minutes but the differnce value is more where the expected time difference should be 9 but as per my code I am getting the wrong value.
Let the PHP DateTime class with diff() method do the work with time calculations.
$now = '10-03-2018 03:53 PM'; // or use simply 'now' for current time
$endTime = '10-03-2018 03:44 PM';
$datetime1 = new DateTime($now);
$datetime2 = new DateTime($endTime);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%i minutes'); // 9 minutes
See it live: https://eval.in/969615

How to get absolute number of months ago in PHP

There a number of questions regarding this, but I couldn't find the exact answer.
$datetime1 = new DateTime('2015-01-15');
$datetime2 = new DateTime(date('Y-m-d'));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%m months');
As today is 2015-05-11 this returns 3 months. I would like it to always assume it's the 1st day of the month for $datetime1 so it should actually return 4 months
I supposed I could use str_replace() or some other string function to lop off the day part of $datetime1 but I'm assuming there is a more elegant method?
Thanks
If '2015-01-15' is variable. You could do:
$date = '2015-01-15';
$datetime1 = new DateTime( date('Y-m-01', strtotime($date)) );
Or use a substring function.
$date = '2015-01-15';
$datetime1 = new DateTime( substr($date, 0, 7).'-01' );
Substring would be faster but strtotime() can handle various formats.

how to calculate days between two days including start date and end date

Consider two dates '2011-01-01' and '2011-01-02'.I want to calculate the number of days between these two dates.The result what I want is 2 days(i.e including both start and end date).I used several date functions in php and mysql,but all returns 1 as the answer.
$date11 = '2011-01-01';
$date22 = '2011-01-02';
$dt1 = new DateTime($date11);
$dt2 = new DateTime($date22);
$diff = $dt2->diff($dt1);
echo $diff->format("%a");
Any solution in php or mysql would be grateful.Thanks in advance.
If you want to get 2 days for this interval you can just +1 to the result, because none of the combinations of functions will give 2 days.
$date11 = strtotime($date11);
$date22 = strtotime($date22);
$diff = $date22 - $date11;
$diff_in_days = floor($diff/(60*60*24)) + 1;
Example
You can use DateTime and DateInterval and do you add 1 day?
DateTime
DateInterval
<?php
$d1 = new DateTime('2011-01-01');
$d2 = new DateTime('2011-01-02');
$d2->add(new DateInterval('24h'));
$interval = $d2->diff($d1);
$interval->format('%d Days');
$interval->format('%h Hours');
?>
in mysql:
select abs(datediff('2011-01-01','2011-01-02'))+1 as difference;
+------------+
| difference |
+------------+
| 2 |
+------------+
1 row in set (0.00 sec)
datediff() returns the number of days between the two dates, abs() makes sure we don't get negative values when switching first and second date and the final +1 because you wanted start and enddate to be included in the number.
Use DateDiff. The online docs have this answer as the first example:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$datetime2->modify("+1 days");
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // output
Another way to do this:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
$diff = $interval->days + 1;
echo $diff . " days.";

Get absolute days away

I want to get the absolute days away a datetime is from today. For example, i would like to know if a date is 2 days away, or 78 days away, or even 5,239 days away (not likely, but you get the idea). I am using an MS SQL database which is returning datetimes where the time components are all 00:00:00.
date_diff returns relative values that you then have to do some crazy math with to get absolute dates do to calculating months, years, etc.
Also, i am having issues getting the date component only of today's date in php.
Edit:
Thanks to mr. w. This is what i ended up with:
$date = $row['AirdateDateTime'];
$today = date_create(date("Y-m-d"));
$away = date_diff($today, $date);
$d = $away->format("%R%a");
The date_create() part was the part i was originally missing to convert to an actual datetime. Also, the format needs to be %R%a. Using %R%d only works for dates in this month.
The date_diff() function (really, the DateTime::diff() method) is what you want, and it's actually not hard. In fact, I think the example in the docs is exactly what you're after:
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%d days');
?>
or
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%d days');
?>
What's returned is a DateInterval object, which you can format any way you want with its format() method. Above, it's being formatted to days, but you have a ton of options; see http://us.php.net/manual/en/dateinterval.format.php.
You shouldn't need to do any math yourself.
[EDIT - forgot this part]
As for getting the date component of today's date, you can do something like this:
<?php
echo date('Y-m-d');
?>
See http://us.php.net/manual/en/function.date.php.
Try this
$date1 = new DateTime('2012-10-28 00:00:00',new DateTimeZone('Europe/London'));
$date2 = new DateTime('2012-10-28 03:00:00',new DateTimeZone('Europe/London'));
$interval = date_diff($date1, $date2);
$format = '%y years, %m months, %d days, %h hours, %i minutes, %s seconds, %a total days %R';
echo $interval->format($format);
if want to change the format try this
http://www.w3schools.com/php/func_date_date.asp
It's probably easiest to convert to unix timestamps (seconds since 1970) and then get the difference.
strtotime() and time() are your friends.
An alternative to what has already been suggested is the DateTime library:
$today = date("Y-m-d");
$today = new DateTime($today);
$future = new DateTime('2010-10-25');
$interval = $today->diff($future);
echo $interval->format('%d days away'); //outputs 17 days away
It sounds like what you want is
<?php
$yourDate = '2010-10-05';
echo ciel((strtotime($yourDate) - time()) / 60 / 60 / 24);

Categories