How to calculate the difference between two dates in PHP.
| PHP Code |
|---|
$century = mktime(12, 0, 0, 1, 1, 2001); $today = time(); $difference = $today - $century; |
| Select all |
The epoche value that can be determined by time() and other PHP functions can be used to easily calculate the difference between two dates. The trick is to convert the dates into time stamps (if not already available in this format). Then the difference between these two time stamps is calculated. The result is the time difference in seconds. This value can then be used to find out how many minutes, hours, and days this corresponds to:
| PHP Code |
|---|
<?php $century = mktime(12, 0, 0, 1, 1, 2001); $today = time(); $difference = $today - $century; echo 'This century started '; echo floor($difference / 84600); $difference -= 84600 * floor($difference / 84600); echo ' days, '; echo floor($difference / 3600); $difference -= 3600 * floor($difference / 3600); echo ' hours, '; echo floor($difference / 60); $difference -= 60 * floor($difference / 60); echo " minutes, and $difference seconds ago."; ?> |
| Select all |
If you start with the number of days, round down each result and substract this from the result; you can also split up the difference into days, hours, and minutes.
Type in the field on the left the code displayed on the image below.
I don't think this will work if you want to include months. There's the problem of leap years and the fact that not all months have the same num. of days
function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
var iWeeks, iDateDiff, iAdjust = 0;
if (dDate2 < dDate1) return -1; // error code if dates transposed
var iWeekday1 = dDate1.getDay(); // day of week
var iWeekday2 = dDate2.getDay();
iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend
iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
// calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)
if (iWeekday1 <= iWeekday2) {
iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
} else {
iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
}
iDateDiff -= iAdjust // take into account both days on weekend
return (iDateDiff + 1); // add 1 because dates are inclusive
}
Warm Regards
Manish Painuly
manishpainuly100@gmail.com
sir i insert some date in database and want to differece between 3 month ago date and todays date please send me the code
Hello sir,
please sove problem
I have two date
ex. 2008-03-22 and 2008-03-25
now I want to display like
2008-03-22, saturday
2008-03-23, sunday
2008-03-24, monday
2008-03-25 , tuesday
hello there.. please help me on how to calculate number of day between 2 dates..
Discuss