PHP DateTime diff - php

This may be a complete noob question but here goes:
I have the following code that compares two dates for absence management. Where I expect the answer to return as 2 (the difference between start and end date) I get 1.
$start_time = new DateTime("2015-01-01 00:00:00");
$end_time = new DateTime("2015-01-02 00:00:00");
$diff = $end_time->diff($start_time);
$d = $diff->days; // 1
I have also tried using just the dates (but I need the times as some absence type are done by hours not days)

Difference is 1 because there is only one day difference between both days.
To convert the datetime into hours or minutes you should look to these links:
Convert datetime into year, month, days, hours, minutes, seconds
Difference between 2 time() values

Related

PHP Show next 7 Days range

I saw this response to a thread and it works but doesn't create a range between the current day and seven days time. Which is what I need. Can anyone give me a hand please?
Update:
An easier way to word it. I want to Select data between two dates. For example current day and seven days time.
My current code:
if($current_day) {
$data['current_day']=date('Y-m-d', strtotime('+7 days'));
$now = new DateTime();
$future_date = new DateTime('2011-05-11 12:00:00');
$interval = $future_date->diff($now);
echo $interval->format("%a days, %h hours, %i minutes, %s seconds");
You can use this code sample if you have php 5.3 or above,
Else try to calculate the difference of two dates in seconds using time() and strtotime(). Then translate those seconds into days/hours/minutes/seconds.

php DateTime diff - include both dates in range?

I have been using DateTime Diff (in php) to get various settings for pairs of dates - two formatted dates to display, a difference from the date to now (eg "start date was 3 months 2 days ago"), and a length between the two dates ("length is 2 months 3 days").
The problem is that DateTime Diff ignores one of the days so if the start is yesterday and the end is tomorrow, it gives 2 days whereas I want 3 because both dates should be included in the length. If it was just days, I could simply add 1 to the result, but I wanted to use the years/months/days results from the Diff and these are determined at construct.
The only way I have found to get the desired results is to create a DateTime for start and end (to get the formatted dates and the differences). Then take the end DateTime, add 1 day to it, then work out the length.
It's a bit clunky but there seems to be no way to tell DateTime Diff to include both start and end dates in the result.
DateTime encapsulates a specific moment in time. "yesterday" is not a moment but a time range. The same for "tomorrow".
DateTime::diff() doesn't ignore anything; it just provides you the exact difference (in day, hours, minutes a.s.o.) between two moments in time.
If you want to get the diff between "tomorrow" and "yesterday" as "3 days" you can subtract the first second of "yesterday" from (one second after the last second of "tomorrow").
Like this:
// Always set the timezone of your DateTime objects to avoid troubles
$tz = new DateTimeZone('Europe/Bucharest');
// Some random time yesterday
$date1 = new DateTime('2016-07-08 21:30:15', $tz);
// Other random time tomorrow
$date2 = new DateTime('2016-07-10 12:34:56', $tz);
// Don't mess with $date1 and $date2;
// clone them and do whatever you want with the clones
$yesterday = clone $date1;
$yesterday->setTime(0, 0, 0); // first second of yesterday (the midnight)
$tomorrow = clone $date2;
$tomorrow->setTime(23, 59, 59) // last second of tomorrow
->add(new DateInterval('PT1S')); // one second
// Get the difference; it is the number of days between and including $date1 and $date2
$diff = $tomorrow->diff($yesterday);
printf("There are %d days between %s and %s (including the start and end date).\n",
$diff->days, $date1->format('Y-m-d'), $date2->format('Y-m-d')
);

Calculate Time difference using UNIX time stamp in PHP [duplicate]

This question already has answers here:
How to calculate the difference between two dates using PHP?
(34 answers)
Closed 9 years ago.
I have 2 unix time, one is todays date and other is expiration time.
Todays Time: 1377173245 (2013-08-22 12:07:25)
Expiration Time: 1406303166 (2014-07-25 15:46:06)
What I want to achieve is calculate remaining time to expire the listing. In current case, it should show, 11 months -- hours -- minutes -- seconds I didn't find any good solution to calculate the difference. I doubt is it possible to calculate time difference using UNIX time system?
Thank you :-)
This is what you're looking for: DateTime::diff
First create object with 1st date:
$date = new DateTime('2013-08-22 12:07:25');
Then use the diff method:
$diff = $date->diff(new DateTime('2014-07-25 15:46:06'));
Now if you print $diff variable, you will see the array containing values for hour, minute, day and so on.
Use DateTime::diff
See the doc on https://www.php.net/manual/en/datetime.diff.php
Try using datetime::diff. Here's the example from the php.net documentation:
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>
It's easy to create a DateTime object using a timespamp. However, this solution requires PHP 5.3+.
Use DateTime class:
Example:
$datetime1 = new DateTime();
$datetime2 = new DateTime('2014-07-25 15:46:06');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%M months, %H hours, %I minutes, and %S seconds remaining ');
Outputs:
11 months, 21 hours, 44 minutes, and 20 seconds remaining
It is most definitely possible. However, you'll run into problems with months, because there are different number of days in each month, so I'll just do days, hours, minutes, and seconds below.
$days=($expiration-$today)/(60*60*24);
$hours=(($expiration-$today)/(60*60))%24; //the modulus operator, gets a remainder
$minutes=(($expiration-$today)/(60))%(60*60);
$seconds=($expiration-$today)/60;
If you need months, you'll find it easier to use date_diff().

php giving wrong answer when using time zone Australia/Sydney

I am developing an website to run in Australia.
so i have set the time zone as follows.
date_default_timezone_set('Australia/Sydney');
I need to calculate number of days between two dates.
I found a strange behavior in the month of October.
$now = strtotime('2013-10-06'); // or your date as well
$your_date = strtotime('2013-10-01');
$datediff = $now - $your_date;
echo floor($datediff/(60*60*24));//gives output 5, this is right
$now = strtotime('2013-10-07'); // or your date as well
$your_date = strtotime('2013-10-01');
$datediff = $now - $your_date;
echo floor($datediff/(60*60*24));//gives output 5, this is wrong, but it should be 6 here
after 2013-10-07 it always give one day less in answer.
Its fine with other timezones. May be its due to daylight saving. But whats the solution for this.
Please help.
Thanks
Why it says 5, and why this is technically correct
In Sydney, DST begins at 2013-10-06 02:00:00 - so you lose an hour in dates straddling that.
When you call strtime, it will interpret the time as a Sydney time, but return a Unix timestamp. If you converted the second set of timestamps to UTC, you'd get a range from 2013-09-30 14:00:00 to 2013-10-06 13:00:00, which isn't quite 6 days, so gets rounded down to 5.
How to get the time difference ignoring DST transitions
Try using DateTime objects instead, e.g.
$tz=new DateTimeZone('Australia/Sydney');
$start=new DateTime('2013-10-01', $tz);
$end=new DateTime('2013-10-07', $tz);
$diff=$end->diff($start);
//displays 6
echo "difference in days is ".$diff->d."\n";
Why does DateTime::diff work differently?
You might ask "why does that work?" - after all, there really isn't 6 days between those times, it's 5 days and 23 hours.
The reason is that DateTime::diff actually corrects for DST transitions. I had to read the source to figure that out - the correction happens inside the internal timelib_diff function. This correction happens if all the following are true
each DateTime uses the same timezone
the timezone must be geographic id and not an abbreviation like GMT
each DateTime must have different DST offsets (i.e. one in DST and one not)
To illustrate this point, here's what happens if we use two times just a few hours either side of the switch to DST
$tz=new DateTimeZone('Australia/Sydney');
$start=new DateTime('2013-10-06 00:00:00', $tz);
$end=new DateTime('2013-10-06 04:00:00', $tz);
//diff will correct for the DST transition
$diffApparent=$end->diff($start);
//but timestamps represent the reality
$diffActual=($end->getTimestamp() - $start->getTimestamp()) / 3600;
echo "Apparent difference is {$diffApparent->h} hours\n";
echo "Actual difference is {$diffActual} hours\n";
This outputs
Apparent difference is 4 hours
Actual difference is 3 hours

how to subtract two dates and times to get difference

i have to sent an email when a user register email contain a link that is become invalid after six hours
what i m doing when email is sent i update the db with field emailSentDate of type "datetime"
now i got the curent date and time and has made to the same formate as it is in db now i want to find that both these dates and time have differenc of 6 hours or not so that i can make link invalid but i donot know how to do this
my code is look like this i m using hardcoded value for db just for example
$current_date_time=date("Y-m-d h:i:s");
$current=explode(" ",$current_date_time);
$current_date=$current[0];
$current_time=$current[1];
$db_date_time="2010-07-30 13:11:50";
$db=explode(" ",$db_date_time);
$db_date=$db[0];
$db_time=$db[1];
i do not know how to proceed plz help
<?php
//$now = new DateTime(); // current date/time
$now = new DateTime("2010-07-28 01:11:50");
$ref = new DateTime("2010-07-30 05:56:40");
$diff = $now->diff($ref);
printf('%d days, %d hours, %d minutes', $diff->d, $diff->h, $diff->i);
prints 2 days, 4 hours, 44 minutes
see http://docs.php.net/datetime.diff
edit: But you could also shift the problem more to the database side, e.g. by storing the expiration date/time in the table and then do a query like
... WHERE key='7gedufgweufg' AND expires<Now()
Many rdbms have reasonable/good support for date/time arithmetic.
What you can do is convert both of your dates to Unix epoch times, that is, the equivalent number of seconds since midnight on the 31st of December 1969. From that you can easily deduce the amount of time elapsed between the two dates. To do this you can either use mktime() or strtotime()
All the best.
$hoursDiff = ( time() - strtotime("2010-07-30 13:11:50") )/(60 * 60);
I'd rather work with a timestamp: Save the value which is returned by "time()" as "savedTime" to your database (that's a timestamp in seconds). Subtract that number from "time()" when you check for your six hours.
if ((time() - savedTime) > 6 * 3600)
// more than 6h ago
or
"SELECT FROM table WHERE savedTime < " . (time() - 6 * 3600)
This might be the solution to your problem -> How to calculate the difference between two dates using PHP?

Categories