Helping ordinary people create extraordinary websites!
 

Calculating date difference more precisely in PHP

by Hasin Hayder


Following this post by Akash Mehta, I thought that a precise dateDiff() function might be helpful for many of you. The following function calculates the difference of two dates in “day” or “month” or “year” more precisely. This function is production ready and you can use it in any of your application which mainly works with these date difference. I have found it somewhere in web, just forgot the source. Thanks to the unknown author of this excellent function.

function datediff($interval, $datefrom, $dateto, $using_timestamps = false)
{

	/*
	$interval can be:
	yyyy - Number of full years
	q - Number of full quarters
	m - Number of full months
	y - Difference between day numbers
	(eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33".
                 The datediff is "-32".)
	d - Number of full days
	w - Number of full weekdays
	ww - Number of full weeks
	h - Number of full hours
	n - Number of full minutes
	s - Number of full seconds (default)
	*/

	if (!$using_timestamps) {
		$datefrom = strtotime($datefrom, 0);
		$dateto = strtotime($dateto, 0);
	}
	$difference = $dateto - $datefrom; // Difference in seconds

	switch($interval) {
		case 'yyyy': // Number of full years
		$years_difference = floor($difference / 31536000);
		if (mktime(date("H", $datefrom),
                              date("i", $datefrom),
                              date("s", $datefrom),
                              date("n", $datefrom),
                              date("j", $datefrom),
                              date("Y", $datefrom)+$years_difference) > $dateto) {

		$years_difference--;
		}
		if (mktime(date("H", $dateto),
                              date("i", $dateto),
                              date("s", $dateto),
                              date("n", $dateto),
                              date("j", $dateto),
                              date("Y", $dateto)-($years_difference+1)) > $datefrom) {

		$years_difference++;
		}
		$datediff = $years_difference;
		break;

		case "q": // Number of full quarters
		$quarters_difference = floor($difference / 8035200);
		while (mktime(date("H", $datefrom),
                                   date("i", $datefrom),
                                   date("s", $datefrom),
                                   date("n", $datefrom)+($quarters_difference*3),
                                   date("j", $dateto),
                                   date("Y", $datefrom)) < $dateto) {

		$months_difference++;
		}
		$quarters_difference--;
		$datediff = $quarters_difference;
		break;

		case "m": // Number of full months
		$months_difference = floor($difference / 2678400);
		while (mktime(date("H", $datefrom),
                                   date("i", $datefrom),
                                   date("s", $datefrom),
                                   date("n", $datefrom)+($months_difference),
                                   date("j", $dateto), date("Y", $datefrom))  7)
                        { // Sunday
		$days_remainder--;
		}
		if ($odd_days > 6) { // Saturday
		$days_remainder--;
		}
		$datediff = ($weeks_difference * 5) + $days_remainder;
		break;

		case "ww": // Number of full weeks
		$datediff = floor($difference / 604800);
		break;

		case "h": // Number of full hours
		$datediff = floor($difference / 3600);
		break;

		case "n": // Number of full minutes
		$datediff = floor($difference / 60);
		break;

		default: // Number of full seconds (default)
		$datediff = $difference;
		break;
	}

	return $datediff;
}





Showcase Your Tutorials

Related Posts
» Give Your Visitors a Relative Time
» Building Web 2.0 Tag Clouds in PHP
» RSS feeds in PHP: 3 simple steps to PHP RSS generation
» Yahoo! UI File Uploader Library
» Converting your traffic into customers
 


This post has 11 Responses so far.
  1. djmmts Says:
    March 14th, 2008 at 2:49 pm

    This is gorgeous. Thanks.

  2. Garry Says:
    April 4th, 2008 at 2:58 pm

    is this function complete, what about the other intervals in the switch statement?

  3. Rajeev Sharma Says:
    May 7th, 2008 at 10:08 pm

    Akash I’m so pleased to read that you acknowledge and thanked the author of this function and made it available for others to be benefited.

    There exist thankless creatures who claim others work. :-)

    This function was written by and available at:
    http://www.ilovejackdaniels.com/php/php-datediff-function/

  4. Akash Mehta Says:
    May 11th, 2008 at 3:16 am

    @Rajeev: Thanks for the heads up. Actually, Hasin Hyder wrote this post, he was merely following on from a similar post I made on “relative time” (see http://www.developertutorials.com/blog/php/give-your-visitors-relative-y-php-69/). He will probably link the original post now that you have pointed it out, but I’ll leave it up to him; the comments on that post are quite useful as well.

  5. ChaBi Says:
    June 23rd, 2008 at 12:14 pm

    Did not work.

  6. abhinav Says:
    July 7th, 2008 at 4:13 am

    how to calculate the diffence between two dates stored in database mysql in the format yyyy-mm-dd (eg. 2008-09-12). date is stored in database in date datatype……
    wating for a sooner reply

  7. Poly Says:
    January 23rd, 2009 at 3:51 am

    Did not work on this line:

    date(“j”, $dateto), date(“Y”, $datefrom)) 7)

    is this

    date(“j”, $dateto), date(“Y”, $datefrom))==7)

    or

    date(“j”, $dateto), date(“Y”, $datefrom)) < 7)

    thanks

  8. Tom Says:
    February 8th, 2009 at 3:43 pm

    I’m getting the same problem as Poly. Any info on this?

  9. Chand Says:
    February 25th, 2009 at 2:10 pm

    function get_time_difference( $start, $end )
    {

    $uts['start'] =$start;
    $uts['end'] =$end;

    if( $uts['start']!=-1 && $uts['end']!=-1 )
    {
    if( $uts['end'] >= $uts['start'] )
    {
    $diff = $uts['end'] – $uts['start'];
    if( $days=intval((floor($diff/86400))) )
    $diff = $diff % 86400;
    if( $hours=intval((floor($diff/3600))) )
    $diff = $diff % 3600;
    if( $minutes=intval((floor($diff/60))) )
    $diff = $diff % 60;
    $diff = intval( $diff );
    return( array(‘days’=>$days, ‘hours’=>$hours, ‘minutes’=>$minutes, ’seconds’=>$diff) );
    }
    else
    {
    return -2;
    //trigger_error( “Ending date/time is earlier than the start date/time”, E_USER_WARNING );
    }
    }
    else
    {
    return -3;
    //trigger_error( “Invalid date/time data detected”, E_USER_WARNING );
    }
    return( false );
    }

  10. Ventzy Says:
    January 9th, 2010 at 5:25 pm

    Indeed there is something missing on “date(“j”, $dateto), date(“Y”, $datefrom)) 7)”.
    Does not work.

  11. jeffery Says:
    January 18th, 2010 at 2:49 am

    great …
    this would work for me…

    it saved me a lot of time….

    thanks for sharing such a good code…

Leave a Reply



GET OUR NEWSLETTERS