Get Difference Between 2 Dates Using PHP

Posted on: Oct 22, 2007 by wenbert

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.


Subscribe to comments Comment | Trackback |
Post Tags: ,

Browse Timeline


Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!