Calculating difference between two dates using PHP:
The following code used to calculating the difference between two dates in PHP without using DateTime class.
The strtotime() function parses date wrote as as string to UNIX timestamp. After substracting two timestamps, $diff is equal to number of seconds between these two days, we wanted to have difference in days, so we need to make additional arithmetic operations and return result. The most important here is use of the same timezone.
The following code used to calculating the difference between two dates in PHP without using DateTime class.
The strtotime() function parses date wrote as as string to UNIX timestamp. After substracting two timestamps, $diff is equal to number of seconds between these two days, we wanted to have difference in days, so we need to make additional arithmetic operations and return result. The most important here is use of the same timezone.
function dateDifference($dt1, $dt2, $timeZone = 'GMT')
{
$tZone = new DateTimeZone($timeZone);
$dt1 = new DateTime($dt1, $tZone);
$dt2 = new DateTime($dt2, $tZone);
$ts1 = $dt1->format('Y-m-d');
$ts2 = $dt2->format('Y-m-d');
$diff = abs(strtotime($ts1)-strtotime($ts2));
$diff/= 3600*24;
return $diff;
}
echo dateDifference('2011-11-11', '2011-12-12');
{
$tZone = new DateTimeZone($timeZone);
$dt1 = new DateTime($dt1, $tZone);
$dt2 = new DateTime($dt2, $tZone);
$ts1 = $dt1->format('Y-m-d');
$ts2 = $dt2->format('Y-m-d');
$diff = abs(strtotime($ts1)-strtotime($ts2));
$diff/= 3600*24;
return $diff;
}
echo dateDifference('2011-11-11', '2011-12-12');
0 comments:
Post a Comment
Share your thoughts here...