How to count days between 2 dates in php

March 11, 2013

A simple solution to count days between 2 dates is using DateTime method since php 5.3

function getDaysBetweenDates($from,$to,$addLastDay = false){
	$d1 = new \DateTime($from);
	$d2 = new \DateTime($to);
	if($addLastDay){
		$d2->add(new \DateInterval('P1D'));
	}
	return $d1 -> diff($d2)->days;
}
echo getDaysBetweenDates('2013-03-01','2013-03-11');
//10
echo getDaysBetweenDates('2013-03-01','2013-03-11',true);
//11

If you need to count the last day too , just pass third parameter – true.

tags: , ,
posted in how to ?, OOP, php by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

4 Comments to "How to count days between 2 dates in php"

  1. Kumar wrote:

    Hello Ivan,
    When we find difference between these days ’2013-03-01′,’2013-03-11′ without last day, i think the results may be 9 starts from 2nd day to 10th day(in this example)(I am not sure about that sir Please Help me)

  2. Kumar wrote:

    Hi Ivan,
    How does the DateInterval() works?
    Thanks

  3. Ivan Gospodinow wrote:

    Hello Kumar,
    if you are counting future dates you need the first day too. So the function is counting right. DateInterval is used as an representation of time. If you want to add 10 days to date time you use new \DateInterval(‘P10D’). See more on http://php.net/manual/en/class.dateinterval.php

  4. Kumar wrote:

    Hello Ivan,
    Sorry for posting the questions here?
    How could i integrate v.me visa payment in php?
    Can you expalain with the steps and code? I am totally confused by that?
    Can you post some example code sir?
    Thank You

Leave Your Comment

 
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org