• Home

Logo

Navigation
  • Home
  • Articles
    • Content Writing
    • Design
    • General
    • Internet Marketing
    • Social Media
    • Tools and Tips
    • Usability
    • Web Hosting Articles
  • Tutorials
    • AJAX Tutorials
    • ASP Tutorials
    • C# Tutorials
    • CGI and Perl Tutorials
    • CSS Tutorials
    • Flash Tutorials
    • HTML Tutorials
    • Illustrator Tutorials
    • Java Tutorials
    • JavaScript Tutorials
    • Linux Tutorials
    • Miscellaneous Tutorials
    • MySQL Tutorials
    • Photoshop Tutorials
    • PHP Tutorials
    • Python Tutorials
    • Wireless Tutorials
    • WordPress Tutorials
    • XML Tutorials
  • Scripts
    • AJAX Scripts
    • ASP Scripts
    • ASP.NET Scripts
    • CGI & Perl Scripts
    • Flash Scripts
    • Java Scripts
    • JavaScript Scripts
    • PHP Scripts
    • Python Scripts
    • Remotely Hosted
    • Tools and Utilities
    • XML Scripts
  • Answers
  • Online Services
  • Tools

Calculating date difference more precisely in PHP

By Hasin Hayder | on Mar 7, 2008 | 13 Comments
PHP Tutorials
  • Tweet
  • Share
  • Tweet
  • Share

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;
}

Share this story:
  • tweet

Author Description

13 Responses to “Calculating date difference more precisely in PHP”

  1. March 14, 2008

    djmmts Log in to Reply

    This is gorgeous. Thanks.

  2. April 4, 2008

    Garry Log in to Reply

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

  3. May 7, 2008

    Rajeev Sharma Log in to Reply

    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. May 11, 2008

    Akash Mehta Log in to Reply

    @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. June 23, 2008

    ChaBi Log in to Reply

    Did not work.

  6. July 7, 2008

    abhinav Log in to Reply

    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. January 23, 2009

    Poly Log in to Reply

    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. February 8, 2009

    Tom Log in to Reply

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

  9. February 25, 2009

    Chand Log in to Reply

    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. January 9, 2010

    Ventzy Log in to Reply

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

  11. January 18, 2010

    jeffery Log in to Reply

    great …
    this would work for me…

    it saved me a lot of time….

    thanks for sharing such a good code…

  12. May 16, 2010

    John H Log in to Reply

    This script is incomplete. The switch case for months references undefined variables required for the calculation.

  13. October 11, 2010

    Anonymous Log in to Reply

    How do we use this? Example function call?

You must be logged in to post a comment.

Connect With Us

RSSSubscribe 1,241Followers 493Likes
  • Popular
  • Recent
  • Comments
  • Creating Energy Spheres in Photoshop

    Apr 15, 2008 - 96 Comments
  • Easy Screen Scraping in PHP with the Simple HTML DOM Library

    Aug 6, 2008 - 20 Comments
  • Extracting text from Word Documents via PHP and COM

    Mar 14, 2008 - 12 Comments
  • When Does Hosting Your Website in the Cloud Make Sense?

    Oct 8, 2010 - 2 Comments
  • Fun with the Microsoft Managed Extensibility Framework Part 2

    Oct 6, 2010 - 0 Comment
  • Fun with the Microsoft Managed Extensibility Framework Part 1

    Sep 22, 2010 - 0 Comment
  • Website Management on the go with the iPad

    I appreciated your post, but I was looking for something I didn't...
    November 24, 2012 - drmoderator
  • Creating Energy Spheres in Photoshop

    I'm a little stuck down here especially at the step of creating the...
    November 23, 2012 - sarah
  • Running background processes in PHP

    Can you give an example? As see it, you can use this only when you...
    November 16, 2012 - Shaked Klein Orbach
Developer Resources
  • Tutorial Directory
  • Learn HTML
  • Learn PHP
  • Learn CSS
  • Learn AJAX
  • Learn JavaScript
  • Learn Pear
  • White Papers
  • Resources
    • NetVisits Web Directory
    • Realtor Pixels
    • Answers On The Run
    • Ask A Geek
  • Recent Posts

    • When Does Hosting Your Website in the Cloud Make Sense?
    • Fun with the Microsoft Managed Extensibility Framework Part 2
    • Fun with the Microsoft Managed Extensibility Framework Part 1
    • Website Management on the go with the iPad
    • Code Contracts in C# 4.0 – Part 1

    Calendar

    May 2013
    M T W T F S S
    « Oct    
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  

    Recent Comments

    • drmoderator on Website Management on the go with the iPad
    • sarah on Creating Energy Spheres in Photoshop
    • Shaked Klein Orbach on Running background processes in PHP
    • Thomas Cuvillier on How To Upload Files Using PHP
    • rizal aditya on Extracting text from Word Documents via PHP and COM
    • Home
    © 2003 - 2013 DeveloperTutorials.com. All Rights Reserved. Privacy Policy.