DEV Community

Discussion on: How to find the difference between two dates in php?

Collapse
 
msamgan profile image
Mohammed Samgan Khan
   /**
     * @param $startPoint
     * @param null $endPoint
     * @return mixed
     */
    function getDuration($startPoint, $endPoint = null)
    {
        if (!$endPoint) {
            $endPoint = time();
        }

        $secs = $endPoint - $startPoint;

        $bit = array(
            ' year' => $secs / 31556926 % 12,
            ' month' => $secs / 2592000 % 12,
            ' day' => $secs / 86400 % 7,
            ' hour' => $secs / 3600 % 24,
            ' minute' => $secs / 60 % 60,
            ' second' => $secs % 60
        );

        foreach ($bit as $k => $v) {
            if ($v > 1) $ret[] = $v . $k . 's';
            if ($v == 1) $ret[] = $v . $k;
        }

        if (!isset($ret)) {
            $ret[0] = 'few seconds';
        }

        return $ret[0];
    }

Use this function, this will give you exact duration between to timestamps. Make sure the start point is in UNIX timestamp format.