PHP將一個日期文字轉換成舉例來說當前的天數

來源:互聯網
上載者:User
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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.