PHP strtotime應(yīng)用經(jīng)驗之談
PHP strtotime應(yīng)用對于我們PHP程序員來說給我們帶來了許多方便之處,我們在實踐中總結(jié)除了一些經(jīng)驗,現(xiàn)分享給大家。我們在使用過程中有不知道有沒有碰到以下情況。#t#
strtotime(date("Y-m-01 00:00:00")); // 用來獲得本月的***天時間戳
在實際PHP strtotime應(yīng)用中突然有一次碰到轉(zhuǎn)換過來的時間比實際時間要慢了 8 小時!本以為是 php.ini中的
timezone 設(shè)置有誤導(dǎo)致,巡查了一圈***把問題鎖定在了strtotime 函數(shù)上(linux服務(wù)器下往往會出問題,WINDOWS服務(wù)器返回的數(shù)據(jù)基本都是正確的)
仔細(xì)讀了下PHP手冊,發(fā)現(xiàn)***個參數(shù) time 有格式要求
time
The string to parse, according to the GNU » Date Input Formats syntax. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored.
通過對 Date Input Formats 的進一步跟進發(fā)現(xiàn)
$ LC_ALL=C TZ=UTC0 date
Mon Mar 1 00:21:42 UTC 2004
$ TZ=UTC0 date +'%Y-%m-%d %H:%M:%SZ'
2004-03-01 00:21:42Z
$ date --iso-8601=ns | tr T ' ' # --iso-8601 is a GNU extension.
2004-02-29 16:21:42,692722128-0800
$ date --rfc-2822 # a GNU extension
Sun, 29 Feb 2004 16:21:42 -0800
$ date +'%Y-%m-%d %H:%M:%S %z' # %z is a GNU extension.
2004-02-29 16:21:42 -0800
$ date +'@%s.%N' # %s and %N are GNU extensions.
@1078100502.692722128
發(fā)現(xiàn)我們常用的格式 yyyy-mm-dd HH:ii:ss 并不符合要求。大致看了下,決定采用UTC0 格式隨將以上代碼更新為以下代碼
strtotime(date("Y-m-01 00:00:00")."Z"); // 用來獲得本月的***天時間戳
至此問題解決!
PHP strtotime應(yīng)用總結(jié):
我們在開發(fā)過程中有時候被系統(tǒng)的支持而忽略了一些細(xì)節(jié)。就如本例在WINDOWS平臺下是不會有這問題,但PHP strtotime應(yīng)用還是要按規(guī)范的走會好些。以避免出現(xiàn)這類問題。