A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Get Difference Between 2 Dates Using PHP

Here is how to get the difference between two dates in PHP.

...
public static function toTimestamp($date){
    $arrayDate=self::toArray($date);
    return mktime($arrayDate['hour'],$arrayDate['minute'],$arrayDate['second'],$arrayDate['month'],$arrayDate['day'],$arrayDate['year']);
}
 
public static function dateDiff($date1,$date2,$unit='HOUR'){
    $date1=self::toTimestamp($date1);
    $date2=self::toTimestamp($date2);
 
    $secs=$date1-$date2;
 
    switch(strtoupper($unit)){
        case 'WEEK':return $secs/60/60/24/7; break;
        case 'DAY':return $secs/60/60/24; break;
        case 'HOUR':return $secs/60/60; break;
        case 'MINUTE':return $secs/60; break;
        case 'SECOND':return $secs; break;
        default:return $secs/60/60; break;
    }
}
...

Usage:

DateFormat::dateDiff($current_tr->requisition_dateTo,$current_tr->requisition_dateFrom,"DAY"));

The static function example above is from an MVC Framework. But you can edit it the sample code to fit your needs.
This tutorial is documented here.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>