PHP Date Difference calculation using mktime function

Calculate calendar differences with DateTime::diff()

Dividing seconds into months or years is only an approximation because calendar units vary in length. Use DateTimeInterface::diff() for calendar-aware differences.

$start = new DateTimeImmutable('2026-09-01');
$end = new DateTimeImmutable('2026-09-14');
$diff = $start->diff($end);
echo $diff->days . ' days';

This current example appears first; the detailed examples below are retained and modernized for comparison and additional use cases.

$d1=mktime(22,0,0,1,1,2007);
$d2=mktime(0,0,0,1,2,2007);
echo "Hours difference = ".floor(($d2-$d1)/3600) . "<br>";
echo "Minutes difference = ".floor(($d2-$d1)/60) . "<br>";
echo "Seconds difference = " .($d2-$d1). "<br>";

echo "Month difference = ".floor(($d2-$d1)/2628000) . "<br>";
echo "Days difference = ".floor(($d2-$d1)/86400) . "<br>";
echo "Year difference = ".floor(($d2-$d1)/31536000) . "<br>";

mktime() : create the timestamp using date and time


To get the difference in minutes we have to divide by 60
To get the difference in hours we have to divide by 3600 ( 60 minute x 60 seconds )
To get the difference tin days we have to divide by 86400 ( 24 x 60 x 60 )
Dividing seconds into months gives only an approximation because months have different lengths.


For elapsed-time calculations you can subtract timestamps, but for calendar-aware differences prefer DateTimeInterface::diff(). Then this difference in seconds is to be converted in to required month, days or year differences. We will try to learn a general way of identification and then format it accordingly.

We will take the two dates with hour, minutes and seconds. If the hour minute and second is not important then we can keep the values as 0. Once both the time stamps are calculated then the difference in seconds are fund out by subtracting the two. For other differences we have to divide the difference in second in different values and taking the floor math value of it.
date difference using date object
PHP Date Functions Generate Timestamp using date and time


Subscribe to our YouTube Channel here



plus2net.com







Sashi

20-03-2010

Thanks for providing this simple and efficient date difference check functionality. It works !
Sadart Abukari

09-07-2011

Great article for all my data manipulation needs. Implemented it with sessions using explode() to turn time stored in session as string and passed it to call_user_func_array with mktime and the exploded array as parameters. Thanks a bunch.
sriram

25-07-2014

nice code
Riddhish

09-04-2015

Really Helpfull




PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer