Chinaunix

标题: PHP将一个日期字符串转换成举例当前的天数 [打印本页]

作者: 听老歌    时间: 2011-03-24 19:01
标题: PHP将一个日期字符串转换成举例当前的天数
本帖最后由 听老歌 于 2011-03-25 10:39 编辑

转:liuzhiqiangruc

PHP将一个日期字符串转换成距离当前的天数




输入为一个日期字符串,例如:2011-3-23

输出为举例当前的天数,例如:1



代码为:



Php代码
  1.   public static function convertDateToLong($dateStr){
  2.         $checkPattern = "/^\d{4}(((-\d{1,2}){2})|((\.\d{1,2}){2})|((\/\d{1,2}){2}))$/";
  3.         $date = substr(trim($dateStr),0,strpos(trim($dateStr)," ")>0 ? strpos(trim($dateStr)," ") : strlen(trim($dateStr)));
  4.         if(preg_match($checkPattern,$date)){
  5.             preg_match("/([-\/.])/",$date,$outer);
  6.             $dilimeter = $outer[1];
  7.             list($year,$month,$day) = explode($dilimeter,$date);
  8.             if(checkdate($month,$day,$year)){
  9.                 $spsec = time()-mktime(0,0,0,$month,$day,$year);
  10.                 if($spsec < 0) throw new Exception("date can not be after today!!!");
  11.                 $spday = floor($spsec/24/60/60);
  12.                 return $spday;
  13.             }
  14.             else{
  15.                 throw new Exception("the date input is not a valid date");
  16.             }
  17.         }
  18.         else{
  19.             throw new Exception("the dateStr is wrong formatted!!!");
  20.         }
  21.     }
复制代码

作者: 紫月亮    时间: 2011-03-24 19:19
这函数写得够复杂。。
作者: bun    时间: 2011-03-24 20:55
提示: 作者被禁止或删除 内容自动屏蔽
作者: bun    时间: 2011-03-24 21:35
提示: 作者被禁止或删除 内容自动屏蔽
作者: wjjchen    时间: 2011-03-25 09:47
回复 1# 听老歌

   不是举例,是距离吧?
    是这个意思吗:echo ceil((strtotime("2011-01-26")-time())/3600/24);




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2