01 January 2010

get time difference in php

Date and time is one function which is always like there in whatever website, project you create. The more simple they look like to start with the more complex they become. Complexity comes in when we put these functions into different loops conditions etc.
 The line below show you how you can call function.
The function expects to be given 2 strings representing the start and end values of a time or date.

<?php

echo 'Hi! My name is Ankit Kumar Chauhan. I am: '.getDifference(date("Y-m-d G:i:s"),'1985-10-02 00:00:00'). '
Years old.';

function getDifference($startDate,$endDate,$format = 6)
{
    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);
    }               
}
?>



No comments:

Post a Comment