note 36250 added to ref.datetime

From: Date: Thu, 02 Oct 2003 10:09:20 +0000
Subject: note 36250 added to ref.datetime
Groups: php.notes 
Request: Send a blank email to php-notes+get-57602@lists.php.net to get a copy of this message
One thing PHP really lacks IMHO is an equivalent of ASP's "DateDiff" function. Here's a function that comes close to duplicating the functionality: <?php function datediff($interval, $date1, $date2) { // Function roughly equivalent to the ASP "DateDiff" function $seconds = $date2 - $date1; switch($interval) { case "y": list($year1, $month1, $day1) = split('-', date('Y-m-d', $date1)); list($year2, $month2, $day2) = split('-', date('Y-m-d', $date2)); $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1)); $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2)); $diff = $year2 - $year1; if($month1 > $month2) { $diff -= 1; } elseif($month1 == $month2) { if($day1 > $day2) { $diff -= 1; } elseif($day1 == $day2) { if($time1 > $time2) { $diff -= 1; } } } break; case "m": list($year1, $month1, $day1) = split('-', date('Y-m-d', $date1)); list($year2, $month2, $day2) = split('-', date('Y-m-d', $date2)); $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1)); $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2)); $diff = ($year2 * 12 + $month2) - ($year1 * 12 + $month1); if($day1 > $day2) { $diff -= 1; } elseif($day1 == $day2) { if($time1 > $time2) { $diff -= 1; } } break; case "w": // Only simple seconds calculation needed from here on $diff = floor($seconds / 604800); break; case "d": $diff = floor($seconds / 86400); break; case "h": $diff = floor($seconds / 3600); break; case "i": $diff = floor($seconds / 60); break; case "s": $diff = $seconds; break; } return $diff; } ?> ---- Manual Page -- http://www.php.net/manual/en/ref.datetime.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+36250 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+36250&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+36250&report=yes

« previous php.notes (#57602) next »