note 48830 deleted from ref.datetime by felipe

From: Date: Mon, 10 Dec 2007 17:45:15 +0000
Subject: note 48830 deleted from ref.datetime by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-133194@lists.php.net to get a copy of this message
Note Submitter: Elizalde Baguinon ---- I evaluated the modified version of Xiven's datediff (below) and I saw some errors. I switched the lines of getting the seconds and the formatting of date. I was testing the datediff() function with a "d" interval. Here I added my test code. $dateA = "2004-12-31"; $dateB = "2005-01-01"; function datediff($interval, $date1, $date2) { // Function roughly equivalent to the ASP "DateDiff" function /* Get the seconds first */ $seconds = strtotime($date2) - strtotime($date1); $date1=date("Y-m-d", strtotime($date1)); $date2=date("Y-m-d",strtotime($date2)); switch($interval) { case "y": list($year1, $month1, $day1) = split('-', $date1); list($year2, $month2, $day2) = split('-', $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": /* parses the year, month and days. split() was replaced with explode(), PHP Manual says it's faster */ list($year1, $month1, $day1) = explode('-', $date1); list($year2, $month2, $day2) = explode('-',$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 the +ve integer only if ($diff<0){ $diff=0-$diff; } return $diff; } echo "x: $dateA<br>"; echo "y: $dateB<br>"; echo "<br>"; echo datediff ("d",$dateA, $dateB);

« previous php.notes (#133194) next »