php date diff in seconds
How do I find the hour difference between two dates in PHP?
I have two dates, formated like «Y-m-d H:i:s». I need to compare these two dates and figure out the hour difference.
10 Answers 10
You can convert them to timestamps and go from there:
Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.
As an addition to accepted answer I would like to remind that \DateTime::diff is available!
The problem is that using these values the result is 167 and it should be 168:
You can try this :
Output:
8 hours 38 minutes 2 seconds
You can use strtotime() to parse your strings and do the difference between the two of them.
Resources :
This is because of day time saving. Daylight Saving Time (United States) 2014 began at 2:00 AM on Sunday, March 9.
Not the answer you’re looking for? Browse other questions tagged php datetime date or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
DateTime::diff
DateTimeInterface::diff
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Description
Returns the difference between two DateTimeInterface objects.
Parameters
The date to compare to.
Should the interval be forced to be positive?
Return Values
The DateInterval object represents the difference between the two dates or false on failure.
Examples
Example #1 DateTime::diff() example
The above examples will output:
Example #2 DateTime object comparison
DateTime objects can be compared using comparison operators.
= new DateTime ( «now» );
$date2 = new DateTime ( «tomorrow» );
The above example will output:
See Also
User Contributed Notes 30 notes
It is worth noting, IMO, and it is implied in the docs but not explicitly stated, that the object on which diff is called is subtracted from the object that is passed to diff.
$date1 = new DateTime(‘now’);
$date2 = new DateTime(‘tomorrow’);
In some situations, this won’t say «in 1 days», but «in 0 days».
I think this is because «now» is the current time, while «tomorrow» is the current day +1 but at a default time, lets say:
Now: 08:00pm, 01.01.2015
Tomorrow: 00:00am, 02.01.2015
In this case, the difference is not 24 hour, so it will says 0 days.
Better use «today», which should also use a default value like:
Today: 00:00am, 01.01.2015
Tomorrow: 00:00am, 02.01.2015
which now is 24 hour and represents 1 day.
This may sound logical and many will say «of course, this is right», but if you use it in a naiv way (like I did without thinking), you can come to this moment and facepalm yourself.
Conclusion: «Now» is «Today», but in a different clock time, but still the same day!
After wrestling with DateTime::diff for a while it finally dawned on me the problem was both in the formatting of the input string and the formatting of the output.
The task was to calculate the duration between two date/times.
1. Make sure you have a valid date variable. Both of these strings are valid:
$strStart = ‘2013-06-19 18:25’ ;
$strEnd = ’06/19/13 21:47′ ;
?>
2. Next convert the string to a date variable
3. Calculate the difference
4. Format the output
[Modified by moderator for clarify]
Using the identical (===) comparision operator in different but equal objects will return false
If you want to quickly scan through the resulting intervals, you can use the undocumented properties of DateInterval.
The function below returns a single number of years, months, days, hours, minutes or seconds between the current date and the provided date. If the date occurs in the past (is negative/inverted), it suffixes it with ‘ago’.
It seems that while DateTime in general does preserve microseconds, DateTime::diff doesn’t appear to account for it when comparing.
= ‘2014-03-18 10:34:09.939’ ;
$val2 = ‘2014-03-18 10:34:09.940’ ;
To work around this apparent limitation/oversight, you have to additionally compare using DateTime::format.
I needed to get the exact number of days between 2 dates and was relying on the this diff function, but found that I was getting a peculiar result with:
I had to end up using :
Though I found a number of people who ran into the issue of 5.2 and lower not supporting this function, I was unable to find any solid examples to get around it. Therefore I hope this can help some others:
Get interval seconds between two datetime in PHP?
8 Answers 8
With DateTime objects, you can do it like this:
You can use strtotime() to do that:
A similar approach is possible with DateTime objects, e.g.
PHP Date Time reference is helpful for things like this: PHP Date Time Functions
strtotime() is probably the best way.
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:
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.
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:
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!
date_diff
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Описание
Эта функция является псевдонимом: DateTime::diff()
User Contributed Notes 20 notes
Powerful Function to get two date difference.
/*
* A mathematical decimal difference between two informed dates
*
* Author: Sergio Abreu
* Website: http://sites.sitesbr.net
*
* Features:
* Automatic conversion on dates informed as string.
* Possibility of absolute values (always +) or relative (-/+)
*/
/* Enjoy and feedback me 😉 */
?>
This behavior looks really weird to me :
PHP is usually relaxed when it comes to data types however that is not the case with date and time. If all you need to do is compare a string date against today’s date you need to do the following:
//Output the array:
echo » ;
?>
This will output the following:
Array
(
[y] => 4
[m] => 10
[d] => 22
[h] => 0
[i] => 0
[s] => 0
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 1787
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
So you can simply use:
Even the top rated comment here, Sergio Abreu’s, doesn’t treat leap years entirely correctly. It should work between 1901 and 2099, but outside that it’ll be a little off.
If you want to find out the number of days between two dates, use below. You can change to a different unit from that. It looks a little insane, but keep in mind the full set of rules for leap years:
So in the functions below, we find the total numbers of days in full years since the mythical 1/1/0001, then add the number of days before the current one in the year passed. Do this for each date, then return the absolute value of the difference.
diff from datetime
My simple function to count up the number of weekdays between the dates (inclusive for both ends), one can add a holidays between the dates to take them into account as well as the weekends, the weekend days could also be changed.
This is a very simple function to calculate the difference between two datetime values, returning the result in seconds. To convert to minutes, just divide the result by 60. In hours, by 3600 and so on.
Here you have in this post http://softontherocks.blogspot.com/2014/12/calcular-la-edad-con-php.html the code to get the age of a person specifying the date of birth:
here a little solution of problem of missing date_diff function with php versions below 5.3.0
Here is how I solved the problem of missing date_diff function with php versions below 5.3.0
The function accepts two dates in string format (recognized by strtotime() hopefully), and returns the date difference in an array with the years as first element, respectively months as second, and days as last element.
It should be working in all cases, and seems to behave properly when moving through February.
I had to find the difference between two days (here is my solution without Date_diff()) :
This function will return count of sunday between inputed dates.
Other data_diff aviable for php5.3>=