Calculating difference in days using PHP Interval Object? - php

I've already seen some answers in StackOverflow about how to calculate difference in time between two dates. But no answer are using the DateTime obejct or the Interval Object in PHP. I got the following code snippet from PHP Manual website: http://www.php.net/manual/en/dateinterval.format.php.
<?php
$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
?>
But the problem is that total days equals 6015 days when it should only be 31 days. I tried to access the instance variable days in the Interval object. It too shows 6015 days. But the instances for month and days intervals are correct. Can someone tell me why?
And I want to use these objects to calculate the difference in times!
Many thanks
UPDATE:
I think it was just a problem with my PHP setup

Running your code...
31 total days
1 month, 0 days
PHP setup issue, perhaps?

I ran that exact same script and got "31 total days" and "1 month, 0 days" (the expected values). Try upgrading your php maybe?..

I'm not sure what version of PHP you're on, but in my experience, I've made it a habit to always set my timezone with date_default_timezone_set('America/Los_Angeles'); where America/Los_Angeles is the timezone you want to be using. I don't know how this ultimately affects the date calculations, but I do know that PHP 5.3 will yell at you if you try and do date manipulation without specifying a default timezone.
I believe you can also set a default timezone in your php.ini- which I think by default is set to UTC.

Related

How to Substract time from datetime

I am using a timezone based script where there is deadline based on timezones. Say for example a deadline is on 7th July at 6PM for a person in IST timezone. The deadline should be 1:30 less than 6pm in Dubai as per their timezone.
I have already calculated the difference between the two timezone difference. I am stuck at deducting that calculated time from the deadline time.
I have saved the timezones in +5:40 +4:00 -4:00 this format instead of using php default ones.
Here's what I use to add and subtract time from a date.
First of all, I get the date from the database and then convert it to a DateTime object.
$date = new DateTime($date);
I use add and a DateInterval to add time. Here's an example to add hours.
$date->add(new DateInterval("PT{$hoursToAdd}H"));
And here's and example to subtract hours intead:
$date->sub(new DateInterval("PT{$hoursToSubstract}H"));
Check this out to know how to work with DateInterval and add/subtract different times: http://php.net/manual/en/class.dateinterval.php
Can you explain a little more specifically what you want to do?
You want to subtract when data already on some var inside your script or you want the SQL query needed ?
If so maybe you can use this answer ---> How to subtract 3 hours from a datetime in MySQL?
The last answer of this post maybe is the one that fit the most what you need :
Assuming you have some timezone issue and know source and destination timezone, you could convert it like so
SELECT
DATE_FORMAT(CONVERT_TZ(x.date_entered, 'UTC', 'Europe/Berlin'), '%Y-%m-%d') AS date
FROM
x
ORDER BY
date ASC;

Strange PHP 5.3 issue with date diff calculating difference in days

I am experiencing a rather strange problem using PHP 5.3's date diff function to calculate the difference in days between two dates. Below is my code:
$currentDate = new DateTime(); // (today's date is 2012-1-27)
$startDate = new DateTime('2012-04-01');
$diff = $startDate->diff($currentDate);
$daysBefore = $diff->d;
echo $daysBefore;
The above code displays 4 as the value of the $daysBefore variable.
Why is PHP displaying a difference of 4 days between the dates 27th Jan 2012 and 1st April 2012, when clearly there are many more days between these dates.
Am I doing something wrong?
DateInterval::$d is the days part of the interval, not the total number of days of the difference. For that, you want DateInterval::$days, so:
$daysBefore = $diff->days;
When creating a DateInterval through the DateTime::diff method, it populates not just days, but hours, minutes, seconds, months and even years in the single character properties. You're checking single-character d for days, which will be the days left over once years and months are calculated.
Try looking at the days property, which only actually gets populated when you use diff.
Behavior here is wildly inconsistent. Check out the DateInterval::format manual page for some interesting information about what happens when you create a DateInterval through various means.
The d property is the number of days as in "3 months, 4 days". If you want the total number of days, use the days property.
4 days, and a couple months...
Use $diff->days for total number of days.
http://www.php.net/manual/en/class.dateinterval.php

What are the pitfalls in the approach to calculate time diff

I wish to calculate the difference b/w 2 times in min:sec format . so is my approch correct
date("i:s",(strtotime($User['end_time']) - strtotime($User['start_time'])));
You may get the problems with timezones on some servers.
A bettter way would be using UTC timezone for calculation:
$date = new DateTime('', new DateTimeZone('UTC'));
$date->setTimestamp(strtotime($User['end_time']) - strtotime($User['start_time']));
echo $date->format('i:s');
Another thing, if they are different in exactly 1 hour, the result will be 00:00
strtotime($User['end_time']) - strtotime($User['start_time']) gives you the difference in seconds. Then you pass it to date, so you get the minute and second of the date whose unix timestamp is that.

Error on strtotime()

$dateTime="2011-10-12 00:00:00";
echo $newDateTime =date("Y-m-d H:i:s", strtotime($dateTime.' -1 hours 30 minutes'));
The result of above code is '2011-10-11 23:30:00'. However, the correct answer should be
2011-10-11 22:30:00.
Is there anying wrong in the code and can anyone help me?
Many thanks
23:30 is the expected result (once you know what is happening).
The relative parts of the string (-1 hours 30 minutes) are processed separately as -1 hours and 30 minutes. They are two instances of the number space? (unit | 'week') format as described in the Relative Formats documentation.
Because of this the cumulative relative change in the time is only -30 minutes, which from midnight gives 23:30.
To get the effect that you desire, either:
use a single relative statement (e.g. -90 minutes)
make your original minutes statement negative as -1 hours -30 minutes
or, use the special ago format as 1 hours 30 minutes ago
See http://php.net/datetime.formats.relative for more details.
date functions aren't fully daylight savings aware. Try using dateTime objects instead

Time difference between a Date and current Time?

Assume I have a funny video site that shows funny videos to users. Below every video, I want to have a statement that says "5 seconds ago", "31 minutes ago", "Yesterday", "2 days ago" based on a timestamp of the video and the current time.
The timestamp that I have is in the format: 2011-10-17 07:08:00.
I'm not too good with dates, but I'm guessing that I need to find the difference between the 2 date/time in seconds, then decide if its between 0sec & 60sec to display in seconds, or between 60sec & 3600sec to display in minutes, or between 3600sec & 3600x24sec to display in hours, between 3600x24sec & 3600x24x2sec to display yesterday, and so on... I believe I should be using strtotime() but I cant seem to find the current time as those solutions I found used new date() which does not seem to work!
How can I do this?
Btw, side question, when I insert 2011-10-17, 7:08PM EDT into a MySQL timestamp column, it gets converted to 2011-10-17 07:08:00 which is AM. How can I get it to be stored in the correct AM/PM?
You can use the DateTime functions of php.
$datetime1 = new DateTime('2011-10-17 07:08:00');
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
From here on you can use some if-statements to output the time difference in another format (seconds, minutes, hours, month, etc.) depending on the actual time difference! The formats for the output are to find here
You can very easily use the DATEDIFF and TIMEDIFF functions of MySQL. Both together tell you exactly how much time has passed.

Categories