PHP將一個日期文字轉換成舉例當前的天數
輸入為一個日期文字,例如:2011-3-23
輸出為舉例當前的天數,例如:1
?
代碼為:
?
public static function convertDateToLong($dateStr){ $checkPattern = "/^\d{4}(((-\d{1,2}){2})|((\.\d{1,2}){2})|((\/\d{1,2}){2}))$/"; $date = substr(trim($dateStr),0,strpos(trim($dateStr)," ")>0 ? strpos(trim($dateStr)," ") : strlen(trim($dateStr))); if(preg_match($checkPattern,$date)){ preg_match("/([-\/.])/",$date,$outer); $dilimeter = $outer[1]; list($year,$month,$day) = explode($dilimeter,$date); if(checkdate($month,$day,$year)){ $spsec = time()-mktime(0,0,0,$month,$day,$year); if($spsec < 0) throw new Exception("date can not be after today!!!"); $spday = floor($spsec/24/60/60); return $spday; } else{ throw new Exception("the date input is not a valid date"); } } else{ throw new Exception("the dateStr is wrong formatted!!!"); } }
1 樓 bardo 2011-03-26
丟開有效性檢驗不說,這個代碼繞的彎子太大了。算天數只要一代碼:
$day=floor((time()-strtotime($date))/86400);
2 樓 liuzhiqiangruc 2011-03-30
bardo 寫道
丟開有效性檢驗不說,這個代碼繞的彎子太大了。算天數只要一代碼:
$day=floor((time()-strtotime($date))/86400);
確實,strtotime是可以的,多謝指點。:-)
3 樓 liuzhiqiangruc 2011-03-30
liuzhiqiangruc 寫道
bardo 寫道
丟開有效性檢驗不說,這個代碼繞的彎子太大了。算天數只要一代碼:
$day=floor((time()-strtotime($date))/86400);
確實,strtotime是可以的,多謝指點。:-)
而且,strtotime支援的日期格式很豐富,學習了。
4 樓 liuzhiqiangruc 2011-03-30
liuzhiqiangruc 寫道
liuzhiqiangruc 寫道
bardo 寫道
丟開有效性檢驗不說,這個代碼繞的彎子太大了。算天數只要一代碼:
$day=floor((time()-strtotime($date))/86400);
確實,strtotime是可以的,多謝指點。:-)
而且,strtotime支援的日期格式很豐富,學習了。
http://www.php.net/manual/en/datetime.formats.date.php