DEV Community

Cover image for How to find the difference between two dates in php?
karthikeyan K
karthikeyan K

Posted on

How to find the difference between two dates in php?

If you were given two dates, that is start date and end date and You want to find the difference between two dates in PHP.

Its very simple and easy to calculate the difference between two dates.
Read More

Top comments (2)

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.

Collapse
 
ri5hirajp profile image
Rishiraj Purohit • Edited

A simple trick is to convert dates to timestamp and then subtracting, you'll get difference in seconds.

$date_stamp = strtotime($date);

Another option is date_diff

php.net/manual/en/function.date-di...