- PHP: Calculate Real Differences Between Two Dates or Timestamps
- PHP dateDiff function for calculating real differences between dates and UNIX timestamps⌗
- dateDiff function example usage⌗
- strtotime examples⌗
- UNIX timestamp and precision examples⌗
- Converting text format back to UNIX timestamp example⌗
- See Also
- How to Get the Date/Time Difference in Seconds Between Two DateTime Objects in PHP?
- Comparing Timestamps to Get Number of Seconds Between Two Dates
- Calculating Number of Seconds Between Two Dates
- How to calculate the difference between two dates using PHP.
- How to calculate the difference between two dates using PHP.
- Difference between now and then.
- Minutes and Days.
- Using DateTime to calculate the difference.
PHP: Calculate Real Differences Between Two Dates or Timestamps
I was using simple function to calculate difference between two dates and timestamps until I noticed, it’s not working correctly in long intervals. It’s very easy to calculate difference between two timestamps in seconds, but it’s much more complicated print difference in human readable format. The Internet can be found in a wide range of ways to do this thing, but as a rule they use a fixed amount of seconds for the year and the month. So if we calculate year with using 365 or 365.25 days and month using 30 or 31 then the difference is not accurate, because of leap years, DST (Daylight Saving Time) and so on.
Because of this problem, I decided to make a function (at least in the short testing) to return the right kind of differences between the UNIX timestamps and dates in human readable format. This function uses PHP strtotime function to calculate real differences and can handle leap years and DST. This function can also return Twitter like about texts with precision parameter.
PHP dateDiff function for calculating real differences between dates and UNIX timestamps⌗
php // Set timezone date_default_timezone_set("UTC"); // Time format is UNIX timestamp or // PHP strtotime compatible strings function dateDiff($time1, $time2, $precision = 6) // If not numeric then convert texts to unix timestamps if (!is_int($time1)) $time1 = strtotime($time1); > if (!is_int($time2)) $time2 = strtotime($time2); > // If time1 is bigger than time2 // Then swap time1 and time2 if ($time1 > $time2) $ttime = $time1; $time1 = $time2; $time2 = $ttime; > // Set up intervals and diffs arrays $intervals = array('year','month','day','hour','minute','second'); $diffs = array(); // Loop thru all intervals foreach ($intervals as $interval) // Create temp time from time1 and interval $ttime = strtotime('+1 ' . $interval, $time1); // Set initial values $add = 1; $looped = 0; // Loop until temp time is smaller than time2 while ($time2 >= $ttime) // Create new temp time from time1 and interval $add++; $ttime = strtotime("+" . $add . " " . $interval, $time1); $looped++; > $time1 = strtotime("+" . $looped . " " . $interval, $time1); $diffs[$interval] = $looped; > $count = 0; $times = array(); // Loop thru all diffs foreach ($diffs as $interval => $value) // Break if we have needed precission if ($count >= $precision) break; > // Add value and interval // if value is bigger than 0 if ($value > 0) // Add s if value is not 1 if ($value != 1) $interval .= "s"; > // Add value and interval to times array $times[] = $value . " " . $interval; $count++; > > // Return string with times return implode(", ", $times); >
dateDiff function example usage⌗
strtotime examples⌗
echo dateDiff("2010-01-26", "2004-01-26") . "\n"; echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n"; echo dateDiff("now", "now +2 months") . "\n"; echo dateDiff("now", "now -6 year -2 months -10 days") . "\n"; echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";
6 years 18 years, 11 months, 30 days, 23 hours, 59 minutes, 59 seconds 2 months 6 years, 2 months, 10 days 4 years, 11 months, 30 days, 8 hours, 21 minutes, 49 seconds
UNIX timestamp and precision examples⌗
echo dateDiff(time(), time()-1000000, 1) . "\n"; echo dateDiff(time(), time()-1000000, 3) . "\n"; echo dateDiff(time(), time()-1000000, 6) . "\n";
11 days 11 days, 13 hours, 46 minutes 11 days, 13 hours, 46 minutes, 40 seconds
Converting text format back to UNIX timestamp example⌗
$time1 = time(); $time2 = $time1-10000000; echo $diff = dateDiff($time1, $time2) . "\n"; echo $time1 . "\n"; echo strtotime(" +".$diff, $time2) . "\n";
3 months, 23 days, 17 hours, 46 minutes, 40 seconds 1264514564 1264514564
See Also
- PHP: Loop through dates (from date to date) with strtotime() function
- PHP CLI Colors – PHP Class Command Line Colors (bash)
- PHP — Measure Scripts Execution Time and Page Generation Time
- PHP stdClass to Array and Array to stdClass – stdClass Object
- BitLy (bit.ly) PHP Class – Shorten and Expand URLs (and Hashes) with BitLy API
- Format bytes with PHP – B, KB, MB, GB, TB, PB, EB, ZB, YB converter
- PHP Script to Generate PostgreSQL Table Partitioning (Part 2)
- CSS compression with own PHP class VS CSSTidy
- Prevent the browsers to use old cached CSS and JS files
- Add Hostname, Date, Time, Uptime, Load Average to Linux Terminal Title
- nginx, PHP 5.3 and FastCGI on CentOS 5.5, Fedora 13, Red Hat RHEL 5.5/6
- Hide Apache ServerSignature / ServerTokens / PHP X-Powered-By
- Add date and time to Linux terminal title (Gnome Terminal, xterm, urxvt, rxvt)
- Google search from Linux and UNIX command line
- Nano Text Editor and nanorc Tips and Tricks
How to Get the Date/Time Difference in Seconds Between Two DateTime Objects in PHP?
By default there’s no method available on the DateTime or DateInterval class to get the difference between two DateTime objects in seconds. Therefore, you can either get the difference of the timestamps of the two dates or calculate the number of seconds yourself:
Comparing Timestamps to Get Number of Seconds Between Two Dates
We can simply compare timestamps of two dates to get the difference in seconds. For example:
$start = new DateTime('2011-12-31 00:00:00'); $end = new DateTime('2021-01-01 00:00:00'); echo $end->getTimestamp() - $start->getTimestamp(); // output: 284169600
Please note that comparing timestamps could lead to problems with dates before 1970 and after 2038.
Calculating Number of Seconds Between Two Dates
You can calculate the number of seconds between the two dates in the following way:
$start = new DateTime('2011-12-31 00:00:00'); $end = new DateTime('2021-01-01 00:00:00'); $diff = $start->diff($end); $daysInSecs = $diff->format('%r%a') * 24 * 60 * 60; $hoursInSecs = $diff->h * 60 * 60; $minsInSecs = $diff->i * 60; $seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->s; echo $seconds; // output: 284169600
The calculation works in the following way:
- Using the %r formatting character, adds the minus sign when the result is negative;
- Using the %a formatting character gives us the total number of days between two dates;
- Using the %r%a format together, we can get the negative/positive number of days. Using that, we can convert the number of days into seconds by multiplying it with hours in a day, minutes in an hour, and seconds in a minute (i.e. days * 24 * 60 * 60 );
- The calculation in the last step does not take into account the hours, minutes and seconds in the date difference (as they’re not included in the %a format). To include those, we simply use the hour, minute and second properties available on the DateInterval object and convert them into seconds as shown in the example above.
Hope you found this post useful. It was published 01 Jan, 2021 . Please show your love and support by sharing this post.
How to calculate the difference between two dates using PHP.
In this guide, we will show you how to calculate the difference between two dates in PHP.
This is useful if you need to figure out how much time has passed between two events.
How to calculate the difference between two dates using PHP.
Let’s say, for example, that we have two date strings:
As you can see, the second date is about one year later than the first one.
However, what if we want to calculate the exact number of seconds that have passed between date one and date two?
//Our dates $date1 = "2013-03-01 19:12:45"; $date2 = "2014-03-01 06:37:04"; //Convert them to timestamps. $date1Timestamp = strtotime($date1); $date2Timestamp = strtotime($date2); //Calculate the difference. $difference = $date2Timestamp - $date1Timestamp; echo $difference;
If you run the code above, you will see that the answer is 31490659.
In other words, 31,490,659 seconds passed between “2013-03-01 19:12:45” and “2014-03-01 06:37:04”.
A basic explanation of what we did:
- We convert both of our date strings into a unix timestamp by using the PHP function strtotime. A unix timestamp represents the number of seconds that have passed since 00:00 on the 1st of January, 1971. After converting them into seconds, we can do some basic subtraction to work out the difference.
- We then subtract the older date from the newer date.
Remember: The older a date is, the smaller its timestamp will be.
If you run the following code, you will see that the 2014 date has a much larger unix timestamp:
$olderDate = "1991-01-02"; $newerDate = "2014-06-07"; echo $olderDate . " is " . strtotime($olderDate), "
"; echo $newerDate . " is " . strtotime($newerDate);
As you can see, “2014-06-07” has a larger timestamp.
This is because more seconds have passed since January 1st, 1971 and June 7th, 2014.
Difference between now and then.
In certain cases, you might need to calculate how many seconds have passed since a given date.
In other words, how much time has passed between “now” and “then”?
//Our dates and times. $then = "2011-02-02 08:00:00"; $now = time(); //convert $then into a timestamp. $thenTimestamp = strtotime($then); //Get the difference in seconds. $difference = $now - $thenTimestamp; echo $difference;
An explanation of this code:
- We retrieve the current timestamp by using the time function.
- We then subtract the older timestamp from our current timestamp.
If you refresh the page a couple of times, you will see that the difference in seconds continues to grow.
Minutes and Days.
In a lot of cases, you will want the number of days or minutes that have passed.
This is because seconds are kind of useless to an end user.
To calculate the number of days that have passed, you can do the following:
//Our "then" date. $then = "2009-02-04"; //Convert it into a timestamp. $then = strtotime($then); //Get the current timestamp. $now = time(); //Calculate the difference. $difference = $now - $then; //Convert seconds into days. $days = floor($difference / (60*60*24) ); echo $days;
As you can see, we were able to convert seconds into days by using some basic math:
- There are 60 seconds in a minute.
- There are 60 minutes in an hour.
- There are 24 hours in a day.
If you multiply the figures above, it will give you 86400, which is the total number of seconds in a day.
If you divide the difference in seconds between our two dates by 86,400, you will get the total number of days that have passed.
You can then use the floor function in order to round the result down. In other words, 2.9 days should become 2 days.
To get the number of minutes, you can simply divide the difference in seconds by 60:
//Our "then" date. $then = "2009-02-04"; //Convert it into a timestamp. $then = strtotime($then); //Get the current timestamp. $now = time(); //Calculate the difference. $difference = $now - $then; //Convert seconds into minutes. $minutes = floor($difference / 60); echo $minutes;
As you can see, most of these calculations are actually pretty simple.
Using DateTime to calculate the difference.
Once you understand the basics of dealing with dates and timestamps in PHP, you can use the DateTime object.
Using DateTime is a better solution simply because it’s cleaner and it provides you with an OO interface.
For example, if we want to get the difference in days using the DateTime object, we can do the following:
$date1 = new DateTime("2011-07-06"); //then $date2 = new DateTime(); //now $diff = $date2->diff($date1)->format("%a"); echo $diff;
The code above is much more concise than the previous examples.
In our final example, we will convert the difference into years, months, days, hours, and minutes:
$then = '2005-09-01 09:02:23'; $then = new DateTime($then); $now = new DateTime(); $sinceThen = $then->diff($now); //Combined echo $sinceThen->y.' years have passed.
'; echo $sinceThen->m.' months have passed.
'; echo $sinceThen->d.' days have passed.
'; echo $sinceThen->h.' hours have passed.
'; echo $sinceThen->i.' minutes have passed.
';
As you can see, the DateTime object is a pretty powerful tool once you figure out how to use it.