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

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

1 5 6 7 8 9 10
    1. Very nice function. This is useful when the PHP version < 5.3. Since version 5.3, PHP supports method Datetime::diff( $datetime1, $datetime2 ); that might be an easier solution.

      Reply
      • Hi Rilwis nice to see you here,

        Yes, this is old post and PHP’s own Datetime:diff is useful on PHP 5.3, but you still need to format output manually. And of course here is many custom modifications from original version… ;)

        Reply
    2. hi all,

      I have a question to all,
      How to calculate minutes “Operational Hours” within a period.

      case example :
      Date range : 2011-11-01 to 2011-11-30,
      Non Operational Hours : between 22:00 to 08:00 week day (Mon to Frid)
      Non Operational Days : Sat + Sun

      Quest :
      How to Calculate Total “Minutes” Operational Time ??

      Please help,
      thanks for your advice …

      BP

      Reply
      • Hi abang,

        Is those Operational days always from Mon to Fri?
        And is those hours fixed 08:00 – 22:00?

        Reply
    3. Heej JR, your script has helped me loads. Thanks thus far! I have a quick question, a problem I can’t simply solve by myself.

      If I do:
      echo dateDiff(1267074000, time(), 3);
      it works fine.

      But if I do:
      echo dateDiff($setTime, $currentTime, 3);
      it doesn’t work, even though holding the same results.
      Is there anything I’m doing wrong?

      Cheers and much thanks in advance.

      Reply
    4. Forgot to add: it gives me 42 years, xx days, etc. I can’t figure out why.

      Reply
      • Hi Ben,

        Could you echo your variables $setTime and $currentTime, just before deteDiff function and post output here, like:

        
        echo $setTime;
        echo $currentTime;
        echo dateDiff($setTime, $currentTime, 3);
        
        Reply
    5. Just pinched this for something too. Thanks a lot mate, works very well!

      Reply
    6. […] recently came across a very simple solution detailed on the following site, PHP: Calculate Real Differences Between Two Dates or Timestamps. One of the best features about the code is that it does not rely on new PHP features such as the […]

      Reply
    7. Beginning of the function is hidden because of remarks in code :)

      Reply
      • oops, now looks good, looks like something loading slowly

        Reply
    8. I hate to bring up a really old post but this has been extremely helpful with my current project. I am doing a project that calculates tenure. An employee can work full-time, or a percentage of time. For example if the employee worked between 01/01/01 and 01/01/02 at full-time I need it to have the result as 1 year but if the employee only worked, say 20 of 40 hours a week (50%), then I should get a result of 6 months. I feel that I should be able to modify the given code to include this but I am still learning PHP and I am having more trouble than I care to admit. Is there any way you or someone else could help me?

      Thank you again.

      Reply
      • Hi Jordan,

        Do you want to get finally exact weeks, days, hours, minutes? And do you have always full months and years?

        Reply
    9. What I really need is just years months and days. between the two dates and then a total amount of days.

      Do i always have full months and years? Yes the dates will always be with full months and years.

      Reply
      • Hi Jordan,

        It’s actually very easy to get just total amount of days between two timestamps with this function just change following line:

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

        To:

        
        $intervals = array('day');
        

        And if you want years, months and days then change it to:

        
        $intervals = array('year','month','day');
        

        You can use this array as a parameter or use simple if…else structure to get it changed using parameter if you want use same function for both.

        Reply
    10. Hi JR..!

      Thank’s for sharing this great script of yours, its very helpful!
      You just saved me from being stuck for days..
      Keep up the good work!

      Thank you so much..!^__^

      planetjane414

      Reply
    11. Very helpful, nice post Cheers :)

      Reply
    12. Hi JR, I able to set the code inside my system. The difference between 2 times display correctly in a table. But the total return the total hour only without ‘days or minute’.. Could you help me figure it out?

      Reply
      • In a row, the time difference output is ok, but when I total it up outside the while loop it calculate the total difference but not presenting in a correct way, example.

        row 1 = 46 hours, 32 minutes
        row 2 = 32 hours, 28 minutes

        Total = 78

        TQ

        Reply
        • Hi FM,

          Could you post your code, how you calculate that total value?

          Reply
          •  
            class TimestampCalc {
            	private $total_seconds;
             
            	public function __construct() {
            		$this->resetTotal();
            	}
             
            	// Reset total time
            	public function resetTotal() {
            		$this->total_seconds = 0;
            	}
             
            	// Time format is UNIX timestamp or
            	// PHP strtotime compatible strings
            	// Returns formatted time
            	public function addTimeDiff($time1, $time2) {
            		// 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;
            		}
             
            		$time = ($time2 - $time1);
             
            		$this->total_seconds += $time;
             
            		return $this->formatTime($time);
            	}
             
            	// Returns plain total time
            	public function getPlainTotal() {
            		return $this->total_seconds;
            	}
             
            	// Returns formatted total time
            	public function getFormattedTotal() {
            		return $this->formatTime($this->total_seconds);
            	}
             
            	private function formatTime($total_seconds) {
            		$diffs = array();
            		$diffs['hour'] =  floor ($total_seconds / (60 * 60));
            		// extract minutes
            		$minutes = $total_seconds % (60 * 60);
            		$diffs['minute'] = floor ($minutes / 60);
            		// extract seconds
            		$seconds = $minutes % 60;
                	$diffs['second'] = $seconds % 60;
             
            		$count = 0;
            		$times = array();
            		// Loop thru all diffs
            		foreach ($diffs as $interval => $value) {
            			// 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);
            	}
            }
            
            $start = $row['course_in'];
            $end = $row['course_out'];
            									
            $tc = new TimestampCalc();
            $formattedTime = $tc->addTimeDiff($start, $end);
            
                                   
            $total = $total+$formattedTime;
            
            Reply
            • Hi FM,

              If you try to get sum of “46 hours, 32 minutes” + “32 hours, 28 minutes” then you get 78, but actually you should calculate total sum first without time formatting and then format time.

              Reply
              • Hi JR. Thanks for the info. Yes I able to do that.

                Reply
                • Hi FM,

                  You are welcome! Nice to hear that you got it working!

                  Reply
    13. I was finding This type of Date Calculation function using PHP from a Long Time…Thanks A lot for this…

      Reply
    14. Using the first code the difference between 01/01/2013 and 31/12/2012 shows 43 years

      Reply
      • Hi Rageesh.PK,

        Date format 31/12/2012 is wrong. Following note from PHP strtotime manual:
        Note:

        Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

        To avoid potential ambiguity, it’s best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

        So you can use following:

        
        // ISO 8601
        echo dateDiff("2013-01-01", "2012-12-31") . "\n";
        
        // European d-m-y format is assumed
        echo dateDiff("01-01-2013", "31-12-2012") . "\n";
        echo dateDiff("01.01.2013", "31.12.2012") . "\n";
        
        // American m/d/y is assumed
        echo dateDiff("01/01/2013", "12/31/2012") . "\n";
        

        So 31/12/2012 is not valid date here.

        Reply
    15. Hi, thanks for share, how can return total days number (2 months+3days = 63days)

      thanks ;)

      Reply
      • Hi paskuale,

        You are welcome!

        If you can use fixed values then just multiply months with 30 and years with 12 * 30 and so on. If you want exact values then you have to use timestamps / dates (from – to) and this function to get exact values.

        Reply
1 5 6 7 8 9 10

Leave a Reply to JR Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close