• Get time difference between two dates in PHP in a specific format

    It is very useful if we get difference between two dates in Minutes,Hours,Days,Weeks,Months and Years. Here, You can derived it by follows the below easy steps :

    Let’s get started:

    Step 1 : Create a PHP file and put below function in it.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    
     
    <?php
    function getDifference($startDate,$endDate,$format = 3)
    {
        list($date,$time) = explode(' ',$endDate);
        $startdate = explode("-",$date);
        $starttime = explode(":",$time);
     
        list($date,$time) = explode(' ',$startDate);
        $enddate = explode("-",$date);
        $endtime = explode(":",$time);
     
        $secondsDifference = mktime($endtime[0],$endtime[1],$endtime[2],
            $enddate[1],$enddate[2],$enddate[0]) - mktime($starttime[0],
                $starttime[1],$starttime[2],$startdate[1],$startdate[2],$startdate[0]);
     
        switch($format){
            // Difference in Minutes
            case 1: 
                return floor($secondsDifference/60);
            // Difference in Hours    
            case 2:
                return floor($secondsDifference/60/60);
            // Difference in Days    
            case 3:
                return floor($secondsDifference/60/60/24);
            // Difference in Weeks    
            case 4:
                return floor($secondsDifference/60/60/24/7);
            // Difference in Months    
            case 5:
                return floor($secondsDifference/60/60/24/7/4);
            // Difference in Years    
            default:
                return floor($secondsDifference/365/60/60/24);
        }                
    }
    ?>

    Step 2 : Now, You can call function which is defined in step 1 and get difference between two dates. Here, in below code you can see how to call that function.

    1
    2
    3
    4
    5
    6
    7
    8
    
     
    <?php
     
    echo "day = ".  getDifference('2011-09-07 10:30:00',date('Y-m-d H:i:s'),'3')."<br>";
    echo "Hours = ".getDifference('2011-09-07 10:30:00','2011-09-07 11:00:00','2')."<br>";
    echo "minutes = ".getDifference('2011-09-07 10:30:00','2011-09-07 09:31:00','1')."<br>";
     
    ?>

    Now, run your php file as created in above steps, by that you will found date differences in Day,Hours and Minutes

Comments on this post

Leave a Reply

  • Security Code :


    × nine = 81