PHP Developer Channel :: 討論園地

您尚未登入。

#1 2005-10-06 12:45:46

ruby
Member
註冊日期: 2005-05-10
文章數: 30

datediff

<?
//date difference function
function datediff($interval, $date1, $date2) {
   // Function roughly equivalent to the ASP "DateDiff" function
   
   //convert the dates into timestamps
  $date1 = strtotime($date1);
  $date2 = strtotime($date2); 
  $seconds = $date2 - $date1;

   //if $date1 > $date2
   //change substraction order
   //convert the diff to +ve integer
   if ($seconds < 0)
   {
           $tmp = $date1;
           $date1 = $date2;
           $date2 = $tmp;
           $seconds = 0-$seconds;           
   }
   
   //reconvert the timestamps into dates
   if ($interval =='y' || $interval=='m') {
       $date1 = date("Y-m-d h:i:s", $date1);
       $date2=  date("Y-m-d h:i:s", $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":     
           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 * 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;
}
?>

最後修改: ruby (2005-10-06 12:46:15)

離線

 

論壇頁尾

Web Hosting
PHP Developer Channel
Powered by PunBB 1.2.9
© Copyright 2002–2005 Rickard Andersson