Substract 2 datetimes - php

I need to substract 2 datetimes, I tried a lot of things but nothing seems to work:
$startime = $historial->getStarttime(); //Datetime
$endtime = $historial->getEndtime(); //Datetime
$mytime = $endtime - $startime;
I also tried with strtotime(), date()...
Any help or clue?

Look at diff() method of DateTime object: http://www.php.net/manual/en/datetime.diff.php
<?php
$interval = $startTime->diff($endTime);
It returns a DateInterval method that you can format as you want: http://www.php.net/manual/en/dateinterval.format.php
<?php
echo $interval->format('%d days');

The substraction operator doesn't work like that, you'll need DateTime::diff():
$diff = $starttime->diff($endtime);
This shall return a DateInterval instance, that you can output in whatever format you want.

$datetime1 = new \DateTime('2009-10-11');
$datetime2 = new \DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
$datetime1->sub($interval);
echo $datetime1->format("Y-m-d"); // 2009-10-09

Related

Get difference between 2 dates with unix

Trying to get the difference between last date vs today.
In a json file, i have unix date:
"lastUpdate": 1568937600,
And i've tried this but with no success.
<?php
$day = $item['lastUpdate'];;
$datetime1 = date_create('$day');
$datetime2 = date_create('now');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a');
?>
Try this:
$datetime1 = new DateTime(date('Y-m-d', $item['lastUpdate'])); //assuming that you have timestamp in the var $item
$datetime2 = new DateTime(date("Y-m-d", strtotime(date("now"))));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a');
Hope it Helps.
Your date_create call on $day is wrong. You need to use double quote to render the variable inside. Also you need an # sign prefix to indicate it to be a timestamp:
<?php
$day = (int) $item['lastUpdate'];
$datetime1 = date_create("#{$day}");
$datetime2 = date_create('now');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a');
?>
Demo: http://sandbox.onlinephpfunctions.com/code/504afecb72bab656bcaf3be8d95bf7f06f5be845
date_create() receives the date/time string in with one of the specific Date and Time Formats. In your case, you're trying to convert a Unix Timestamp to a DateTime object. You can do that properly by replacing the following line:
$datetime1 = date_create('$day');
with:
$datetime1 = date_create('#'.$day);

Date_Diff not returning desired result

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;

How to calculate the difference of datetime field and now in Cakephp?

I have a datetime field in my database that contains the following information:
2015-08-04 18:59:01
I want to check the difference between that datetime field and now using Cakephp framework ?
See DateTime::diff
$date = '2015-08-04 18:59:01';
$dateTime = new DateTime($date);
$now = new DateTime();
$interval = $now->diff($dateTime);
echo $interval->format('%R%a days');
See DateInterval::format for other formatting options.
You can also get diff in seconds:
$date = '2015-08-04 18:59:01';
$dateTime = new DateTime($date);
$diff = time() - $dateTime->getTimestamp();
Calculate the difference between two dates:
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
Output:
+272 days
The date_diff() function returns the difference between two DateTime objects.

Get hours out of a datetime

Trying to get the hours in 24 hours format from a datetime and nothing works:
$date=date_create("now");
date_add($date,date_interval_create_from_date_string('3 hours'));
$finalDate = date_format($date,"Y-m-d H:i:s");
// $finalDate is "2013-12-25 15:06:45"
Tried the following:
date('H', $finalDate)); // getting 02
date('G', $finalDate)); // getting 02
$finalDate->hours); // getting nothing
date_format($finalDate,"H")); // getting nothing
Read all posts in this site, nothing solved it for me...
$date is already an DateTime object.
All you need to do is:
$hour = date_format($date, 'H');
or
$hour = $date->format('H');
PS: Object oriented style is recommended over Procedural style.
With DateTime and "object syntax":
<?php
$date = new DateTime();
$date->modify('+3 hours');
echo $date->format('H');
?>
Please use the newer DateTime object. I also added the out commented variant of how to see the difference between two different DateTime objects.
$date1 = new DateTime('2013-12-15 12:00:00');
$date2 = new DateTime('2013-12-25 13:30:30');
//$interval = $date1->diff($date2);
//$diff = $interval->format('%d');
//echo $diff;
echo $date1->format('H');
You can use the PDO variant of $date->add() to write what you did a little cleaner :)
Try this:
$timeStr=strtotime($finalDate);
echo date('H', $timeStr);

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