# PHP: Calculate Real Differences Between Two Dates or Timestamps - Comment Page: 8

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...

## 226 comments on “PHP: Calculate Real Differences Between Two Dates or Timestamps - Comment Page: 8”

1 6 7 8 9 10
1. I would like to limit the output from this (2 days, 18 hours, 42 minutes, 24 seconds) to only outputting the two longest times. So in the example given, when I echo dateDiff() I would only get 2 day, 18 hours. Once we are down to less than 1 day, then (18 hours, 42 minutes) would be output.

Is there an easy way to do this in your function?

• Hi John,

Actually you can use this dateDiff function directly, when you set precision = 2, like:

``````
echo dateDiff(time(), time()-39671, 2) . "\n";
echo dateDiff(time(), time()-111611, 2) . "\n";
echo dateDiff(time(), time()-3628811, 2) . "\n";
echo dateDiff(time(), time()-36288011, 2) . "\n";
``````

Output:

```11 hours, 1 minute
1 day, 7 hours
1 month, 11 days
1 year, 1 month
```

One additional thing to note, if you test following example:

``````
echo dateDiff(time(), time()-259201, 2) . "\n";
``````

Output:

```3 days, 1 second
```

If you want remove seconds completely then modify intervals array:

``````
\$intervals = array('year','month','day','hour','minute','second');
``````

To

``````
\$intervals = array('year','month','day','hour','minute');
``````
2. This is such a useful function! Many thanks :)

3. hello JR,
i would like to ask you that how can i use these date functions so that i can use them for my articles publishing .
like “posted ___ seconds/hours/days/years ago”
i tried a code but it isn’t working for me.
plz help me out

• Hi Shiv,

This code should work just as you want. So could you tell more about your problem?

• Hi Mate,I am having an exam in PHP next week.there was a sample question that might come to exam if you can show me how to do that that will be great,
every time the client submit a number the page will tell them the different between it and the previous number they entered and how many seconds it has been since they submitted the previous number.

many thanks.

• Hi sabri,

Here is one possible solution using text file as data store. This is not polished code, just quickly written ugly code. :)

``````

Show diff

Difference (value):

Difference (sencods):

``````

If you are using Linux or Mac, then this should work without any modifications, but if you use Windows then check \$file location. So copy paste this code somefilename.php and run from your web server.

• Thank you very much..you save my life

• Hi JR,
Form a page name “numbers,php” which uses sessions to calculate the different between numbers.

<form name="numbers" method="post" action="numbers"
enter a number;

every time the client submit a number the page will tell them the difference between it and the previous
number they entered and how many seconds it has been since they sumbmittde the previous number.
write the php code which goes below the form on this page in order to implement the functionality described.

*check if a session variable named”time”exists and if it doesnt then,
-create a session”time”and give it a value of the current unix timestamp
-create \$-session [number]and give it a value of 0.

thanks

• Hi again sabri,

Try following code:

``````

Show diff

Difference (value):

Difference (sencods):

``````

Check also that number exists and both time & number should be numeric.

• Thank you very much JR,your simply awesome:)

4. i was wondering how can i write the interval array in norwegian, i tryed it but then my site goes bananas (loading all the time and freezes) :/

• Hi Kris,

You have to create separate array for norwegian intervals, because this function uses those english intervals with strtotime function.

I recommend you to do full mapping with interval names (singular and plural), like:

``````
...
...
``````

Then simply replace following:

``````
\$times[] = \$value . " " . \$interval;
``````

with:

``````
\$times[] = \$value . " " . \$intervals_no[\$interval];
``````
5. I need output below like this way 2013.02.07 8:25:36 how do i do this.

• Hi Mahesh,

You can’t display difference between two dates in this format? Or could you explain what you try to do?

6. I am not getting correct months and days using this function when the start date is 29, 30 or 31 of any month and the end date is 31 May 2013.
I tried with following dates
Start: 2012-09-29 End: 2013-05-31 Output: 7 months, 30 days
Start: 2012-09-30 End: 2013-05-31 Output: 7 months, 29 days
Start: 2012-09-31 End: 2013-05-31 Output: 7 months, 30 days

• Hi San,

If you checked your start dates, then you see that 2012-09-31 is not real date, right?

And output of 2012-09-29 and 2012-09-30 looks good?

• Ok, 2012-09-31 is not real date but you see the output is not correct with 2012-09-29 and 2012-09-30.

Correct output should be following

Start: 2012-09-28 End: 2013-05-31 Output: 8 months, 3 days //Correct
Start: 2012-09-29 End: 2013-05-31 Output: 7 months, 30 days //Incorrect
Correct output should be 8 months 2 days
Start: 2012-09-30 End: 2013-05-31 Output: 7 months, 29 days //Incorrect
Correct output should be 8 months 1 day

• Hi San,

It take a while to figure out whats happening, but you are exactly right. It’s hard to say that is this even PHP bug, but I can explain you this. If you try following code you will see something interesting:

``````
``````
``` So both PHP functions strtotime and mktime shows different final values if you add 8 months once or if you add 8 times one month, which is really strange to me, but yes this is the case. So I made quickly following replace to interval loop: ... // 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; } ... This actually tries every interval until \$ttime is more than \$time2, and then add needed value to \$time1 and move to the next interval and do same thing etc. So if we think your case, this version add 8 months once (when it first try 1,2,3,4,5,6,7) instead adding 8 times one month. If you replace "// Loop thru all intervals" loop with this, is it working then as expected? :) Reply ```
``` ```
``` San 22nd May 2013, 11:32 am Thanks, it seems to be working fine with this change. I am going through a lot more date comparisons at the moment and will come back to you if I notice anything wrong. Reply ```
• ``` ```
``` ```
• ``` ```
``` ```
• ``` ```
``` ```
7. ``` Carlos 6th May 2013, 6:58 pm Very nice work JR Reply Enissae 7th August 2013, 9:41 pm Nice work… But maybe consider making the possibility to get the result in days only, or hours only …. Reply Postarinn 22nd January 2014, 6:07 am Hi, I really like this code, it is really good, the only thing I would like to do is to display text when date reached, like for countdown to christmas, when reached display merry christmas. Rather then counting backwards too. Is this possible with this code somehow? Reply Melbourne 28th February 2014, 12:49 pm Thank you……for very useful code….:) Reply Jamie 20th March 2014, 2:08 pm I have noticed if you use this class and use two dates that are the same it does not reply correctly. for example. \$firsttimestamp = ‘1395229055’; \$secondtimestamp =’1395231544′; \$date = date(“Y-m-d”, \$firsttimestamp) ; \$time = date(“g:i a”, \$firsttimestamp) ; \$end_date = date(“Y-m-d”,\$secondtimestamp) ; \$end_time = date(“g:i a”,\$secondtimestamp) ; Reply JR 21st March 2014, 1:04 pm Hi Jamie, So this function returns 41 minutes, 29 seconds, which is exactly what it should be? Difference in seconds 1395231544 – 1395229055 = 2489 seconds. 41 * 60 = 2460 2489 – 2460 = 29 So it’s 41 minutes 29 seconds? Reply kamlesh 7th July 2014, 4:59 pm i need output in the format: 0 years, 0 months, 0 days, 15 hours, 0 minutes, 12 seconds that is aal the parameters with their values,if their is no value then it should be 0 and the interval name. Thanks. Reply JR 28th September 2014, 2:24 pm Hi kamlesh, I’m sorry, but I have totally missed your question. If you still looking answer to this, then you could simply commment out two rows from dateDiff function: // 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++; //} Reply swati 26th September 2014, 9:40 am hi sir, I want to show the time diffrences between current date & time and database date & time. its show the differences but I want to show like if minimum time in second then show second, if uper in second then show minute, if time uper in minute then show hour, if uper in hours then show day. how it would be done sir… Reply JR 28th September 2014, 2:17 pm Hi swati, Try simply following: echo dateDiff('2014-09-14 10:00:01', '2014-09-14 10:00:07', 1) . PHP_EOL; echo dateDiff('2014-09-14 10:00:01', '2014-09-14 10:01:07', 1) . PHP_EOL; echo dateDiff('2014-09-14 10:00:01', '2014-09-14 11:00:07', 1) . PHP_EOL; echo dateDiff('2014-09-14 11:00:01', '2014-09-15 11:00:07', 1) . PHP_EOL; echo dateDiff('2014-09-14 11:00:01', '2014-10-14 11:00:07', 1) . PHP_EOL; echo dateDiff('2014-09-14 11:00:01', '2015-09-14 11:00:07', 1) . PHP_EOL; Output: 6 seconds 1 minute 1 hour 1 day 1 month 1 year Reply Rusty 11th November 2014, 7:03 pm Great script/chunk of code here. Anyway to easily add in excluding weekends? I saw some additional code that excluded weekends, but we cannot seem to get it to work correctly. I might be missing something. Reply Archana 21st November 2014, 12:44 pm Thanks Mr.JR , your code is working like a charm , thanks for sharing. Reply ```
``` ```
``` « Previous 1 … 6 7 8 9 10 Next » Leave a Reply to JR Cancel replyYour email address will not be published. Required fields are marked *Comment * Name * Email * Website Δdocument.getElementById( "ak_js_1" ).setAttribute( "value", ( new Date() ).getTime() ); This site uses Akismet to reduce spam. Learn how your comment data is processed. ```
``` ```
``` ```
``` (adsbygoogle = window.adsbygoogle || []).push({}); Please support us and subscribe to inttf Youtube channel! ```
``` Last updated posts Fedora 36/35/34 NVIDIA [515.48.07 / 510.73.05 / 470.129.06 / 390.151 / 340.108] Drivers Install Guide Install NVIDIA [515.48.07 / 510.73.05 / 470.129.06 / 390.151 / 340.108] Drivers on Debian / Ubuntu / Linux Mint / LMDE Install NVIDIA Drivers [515.48.07 / 510.73.05 / 470.129.06 / 390.151 / 340.108] on CentOS Stream 9/8, RHEL 9/8, Rocky Linux 8.5 openSUSE 15.4 / 15.3 / Tumbleweed NVIDIA [515.48.07/ 510.73.05 / 470.129.06 / 390.151 / 340.108] Drivers Install Guide inttf NVIDIA 340.xx, 390.xx, 418.xx, 435.xx Patcher for Kernel 5.18/5.17/5.16/5.15/5.14/5.13 [BASH Script] Latest posts inttf-kernel - Clear Linux kernel for Fedora 36 users Upgrade to Fedora 36 from Fedora 35 using DNF Fedora 36 Workstation Installation Guide / Gnome 42 Quick Tour and New Features openSUSE Leap 15.4 Installation Guide [USB Media Creation, Multiboot, Gnome 41 Quick Tour] openSUSE 15.4 / 15.3 / Tumbleweed NVIDIA [515.48.07/ 510.73.05 / 470.129.06 / 390.151 / 340.108] Drivers Install Guide Most popular posts Fedora 36/35/34 NVIDIA [515.48.07 / 510.73.05 / 470.129.06 / 390.151 / 340.108] Drivers Install Guide VirtualBox 6.1.28 / 6.1.29 on Fedora 35/34/33, CentOS/RHEL 8/7 Install Skype 8.69 on Fedora 34/33, CentOS/RHEL/SL 8.3/7.8 Fedora 16 nVidia Drivers Install Guide (disable nouveau driver) Install Google Chrome on Fedora 36/35, CentOS Stream 9/8, Red Hat (RHEL) 9/8, Rocky Linux 8.5 © If Not True Then False | Terms of Service / Disclaimer | Privacy Policy ```
``` Go to mobile version Close function lCSS(src, onload = null){ var s = document.createElement('link'); s.href = src; s.rel = 'stylesheet'; s.type = 'text/css'; if (onload != null) { var a = document.createAttribute('onload'); a.value = onload; s.setAttributeNode(a); } document.getElementsByTagName('head')[0].appendChild(s); } //lCSS('https://fonts.googleapis.com/css?family=Lato:400,700', "document.documentElement.className+=' fontsloaded';"); lCSS('/wp-content/themes/inttf/css/prism.css'); lCSS('/wp-content/themes/inttf/css/baguetteBox.min.css'); document.querySelector('li.search a').addEventListener('click', function(){ var o = document.getElementById('sov'); var st = o.currentStyle ? o.currentStyle.display : getComputedStyle(o, null).display; if (st === "none") { o.style.display = "block"; } else { o.style.display = "none"; } }); document.querySelector('#sov .close').addEventListener('click', function(){ document.getElementById('sov').style.display = "none"; }); window.addEventListener('load', function() { if (typeof baguetteBox !== 'undefined') { baguetteBox.run('.entry-content'); } }); ```