This is correctly working time differentiating function. It's resistant to problems with leap year and different days of month. Inputs are two timestamps and function returns array with differences in year, month, day, hour, minute a nd second.
<?php
function date_diff($d1, $d2){
/* compares two timestamps and returns array with differencies (year, month, day, hour, minute, second)
*/
//check higher timestamp and switch if neccessary
if ($d1 < $d2){
$temp = $d2;
$d2 = $d1;
$d1 = $temp;
}
else {
$temp = $d1; //temp can be used for day count if required
}
$d1 = date_parse(date("Y-m-d H:i:s",$d1));
$d2 = date_parse(date("Y-m-d H:i:s",$d2));
//seconds
if ($d1['second'] >= $d2['second']){
$diff['second'] = $d1['second'] - $d2['second'];
}
else {
$d1['minute']--;
$diff['second'] = 60-$d2['second']+$d1['second'];
}
//minutes
if ($d1['minute'] >= $d2['minute']){
$diff['minute'] = $d1['minute'] - $d2['minute'];
}
else {
$d1['hour']--;
$diff['minute'] = 60-$d2['minute']+$d1['minute'];
}
//hours
if ($d1['hour'] >= $d2['hour']){
$diff['hour'] = $d1['hour'] - $d2['hour'];
}
else {
$d1['day']--;
$diff['hour'] = 24-$d2['hour']+$d1['hour'];
}
//days
if ($d1['day'] >= $d2['day']){
$diff['day'] = $d1['day'] - $d2['day'];
}
else {
$d1['month']--;
$diff['day'] = date("t",$temp)-$d2['day']+$d1['day'];
}
//months
if ($d1['month'] >= $d2['month']){
$diff['month'] = $d1['month'] - $d2['month'];
}
else {
$d1['year']--;
$diff['month'] = 12-$d2['month']+$d1['month'];
}
//years
$diff['year'] = $d1['year'] - $d2['year'];
return $diff;
}
$born_date = mktime(6,30,0,7,24,2008);
$date_diff_array = date_diff($born_date, time());
print_r($date_diff_array);
?>
Description
This function is an alias of: DateTime::diff
date_diff
davix
06-Oct-2009 03:46
06-Oct-2009 03:46
mark at dynom dot nl
02-Jul-2009 08:44
02-Jul-2009 08:44
If you simply want to compare two dates, using conditional operators works too:
<?php
$start = new DateTime('08-06-1995 Europe/Copenhagen'); // DD-MM-YYYY
$end = new DateTime('22-11-1968 Europe/Amsterdam');
if ($start < $end) {
echo "Correct order";
} else {
echo "Incorrect order, end date is before the starting date";
}
?>
tom at knapp2meter dot tk
16-Apr-2009 11:06
16-Apr-2009 11:06
A simple way to get the time lag (format: <hours>.<one-hundredth of one hour>).
Hier ein einfacher Weg zur Bestimmung der Zeitdifferenz (Format: <Stunden>.<hundertstel Stunde>).
<?php
function GetDeltaTime($dtTime1, $dtTime2)
{
$nUXDate1 = strtotime($dtTime1->format("Y-m-d H:i:s"));
$nUXDate2 = strtotime($dtTime2->format("Y-m-d H:i:s"));
$nUXDelta = $nUXDate1 - $nUXDate2;
$strDeltaTime = "" . $nUXDelta/60/60; // sec -> hour
$nPos = strpos($strDeltaTime, ".");
if (nPos !== false)
$strDeltaTime = substr($strDeltaTime, 0, $nPos + 3);
return $strDeltaTime;
}
?>
