<code><?<br />/**<br />* 转换为UNIX时间戳<br />*/<br />function gettime($d) {<br /> if(is_numeric($d))<br /> return $d;<br /> else {<br /> if(! is_string($d)) return 0;<br /> if(ereg(":",$d)) {<br /> $buf = split(" +",$d);<br /> $year = split("[-/]",$buf[0]);<br /> $hour = split(":",$buf[1]);<br /> if(eregi("pm",$buf[2]))<br /> $hour[0] += 12;<br /> return mktime($hour[0],$hour[1],$hour[2],$year[1],$year[2],$year[0]);<br /> }else {<br /> $year = split("[-/]",$d);<br /> return mktime(0,0,0,$year[1],$year[2],$year[0]);<br /> }<br /> }<br />}</code><code>/**<br />*<br />* DateAdd(interval,number,date)<br />* 返回已添加指定时间间隔的日期。<br />* Inetrval为表示要添加的时间间隔字符串表达式,例如分或天<br />* number为表示要添加的时间间隔的个数的数值表达式<br />* Date表示日期<br />*<br />* Interval(时间间隔字符串表达式)可以是以下任意值:<br />* yyyy year年<br />* q Quarter季度<br />* m Month月<br />* y Day of year一年的数<br />* d Day天<br />* w Weekday一周的天数<br />* ww Week of year周<br />* h Hour小时<br />* n Minute分<br />* s Second秒<br />* w、y和d的作用是完全一样的,即在目前的日期上加一天,q加3个月,ww加7天。<br />*/<br />function DateAdd($interval, $number, $date) {<br /> $date = gettime($date);<br /> $date_time_array = getdate($date);<br /> $hours = $date_time_array["hours"];<br /> $minutes = $date_time_array["minutes"];<br /> $seconds = $date_time_array["seconds"];<br /> $month = $date_time_array["mon"];<br /> $day = $date_time_array["mday"];<br /> $year = $date_time_array["year"];<br /> switch ($interval) {<br /> case "yyyy": $year +=$number; break;<br /> case "q": $month +=($number*3); break;<br /> case "m": $month +=$number; break;<br /> case "y":<br /> case "d":<br /> case "w": $day+=$number; break;<br /> case "ww": $day+=($number*7); break;<br /> case "h": $hours+=$number; break;<br /> case "n": $minutes+=$number; break;<br /> case "s": $seconds+=$number; break;<br /> }<br /> $timestamp = mktime($hours ,$minutes, $seconds,$month ,$day, $year);<br /> return $timestamp;<br />}<br />/**<br />* DateDiff(interval,date1,date2)<br />* 返回两个日期之间的时间间隔<br />* intervals(时间间隔字符串表达式)可以是以下任意值:<br />* w 周<br />* d 天<br />* h 小时<br />* n 分钟<br />* s 秒<br />*/<br />function DateDiff ($interval, $date1,$date2) {<br /> // 得到两日期之间间隔的秒数<br /> $timedifference = gettime($date2) - gettime($date1);<br /> switch ($interval) {<br /> case "w": $retval = bcdiv($timedifference ,604800); break;<br /> case "d": $retval = bcdiv( $timedifference,86400); break;<br /> case "h": $retval = bcdiv ($timedifference,3600); break;<br /> case "n": $retval = bcdiv( $timedifference,60); break;<br /> case "s": $retval = $timedifference; break;<br /> }<br /> return $retval;<br />}<br />?><br /><?<br />// 测试例<br />$d1 = "2002-01-11";<br />$d2 = date("Y-m-d",dateadd("d",15,$d1));<br />echo $d1."的". datediff("d",$d1,$d2)."天后是$d2<br>";<br />echo $d1."的10天前是".date("Y-m-d",dateadd("d",-10,$d1))."<br>";<br />$d3 = date("Y/m/d H:i:s");<br />echo "现在是".$d3."距离2002/2/12 12:59:59还有".datediff("s",$d3,"2002/2/12 12:59:59")."秒<br>";<br />?></code>