Difference between two strtotime and date in php and convert seconds into other time format

In this quick tutorial, I will let you know how to convert second into date format, this is a very common problem in web development to convert date into a specific date format.
To achieve the above results we need to convert the date into a timestamp then we converted that timestamp into the desire date format with help of the date(timestamp, ‘date format’) function.
But here we are converting seconds into a user-specific date format like we want to show as below format date.

Here is a code to find the difference between 2 dates in various formats

//get Date diff as intervals 
$date1 = new DateTime(“2021-03-13 00:00:00”);
$date2 = new DateTime(“2021-03-18 01:23:45”);
$interval = $date1->diff($date2);
$diffInSeconds = $interval->s;  // difference in seconds  
$diffInMinutes = $interval->i;  // difference in Minuts   
$diffInHours   = $interval->h;  // difference in Hours    
$diffInDays    = $interval->d;  // difference in Days    
$diffInMonths  = $interval->m;  // difference in Month   
$diffInYears   = $interval->y;  // difference in Year   

//or get Date difference as total difference
$d1 = strtotime(“2018-01-10 00:00:00”);
$d2 = strtotime(“2019-05-18 01:23:45”);
$totalSecondsDiff = abs($d1-$d2);                     // difference in seconds
$totalMinutesDiff = $totalSecondsDiff/60;             // difference in Minutes 
$totalHoursDiff   = $totalSecondsDiff/60/60;          // difference in Hours  
$totalDaysDiff    = $totalSecondsDiff/60/60/24;       // difference in Days   
$totalMonthsDiff  = $totalSecondsDiff/60/60/24/30;    // difference in Month  
$totalYearsDiff   = $totalSecondsDiff/60/60/24/365;   // difference in Year   

Convert seconds into other time format

To Convert seconds to Hour:Minute:Second in php just use this code-

function secondstoDays($seconds)
{
    $ret = “”;

    /*** get the days ***/
    $days = intval(intval($seconds) / (3600*24));
    if($days> 0)
    {
        $ret .= “$days days “;
    }

    /*** get the hours ***/
    $hours = (intval($seconds) / 3600) % 24;
    if($hours > 0)
    {
        $ret .= “$hours hours “;
    }

    /*** get the minutes ***/
    $minutes = (intval($seconds) / 60) % 60;
    if($minutes > 0)
    {
        $ret .= “$minutes minutes “;
    }

    /*** get the seconds ***/
    $seconds = intval($seconds) % 60;
    if ($seconds > 0) {
        $ret .= “$seconds seconds”;
    }

    return $ret;
}

Tags: No tags

Leave A Comment

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