PHP程序员特别是初学者们在PHP strtotime应用中经常会出现一些错误。我们需要不断的学习积累这些错误经验,以达到灵活编写代码。

PHP strtotime应用对于我们PHP程序员来说给我们带来了许多方便之处,我们在实践中总结除了一些经验,现分享给大家。我们在使用过程中有不知道有没有碰到以下情况。#t#

PHP strtotime应用经验之谈(PHP strtotime)  strtotime应用 第1张

strtotime(date("Y-m-01 00:00:00")); // 用来获得本月的***天时间戳

在实际PHP strtotime应用中突然有一次碰到转换过来的时间比实际时间要慢了 8 小时!本以为是 PHP.ini中的

timezone 设置有误导致,巡查了一圈***把问题锁定在了strtotime 函数上(linux服务器下往往会出问题,WINDOWS服务器返回的数据基本都是正确的)

仔细读了下PHP手册,发现***个参数 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 的进一步跟进发现

$ 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

发现我们常用的格式 yyyy-mm-dd HH:ii:ss 并不符合要求。大致看了下,决定采用UTC0 格式随将以上代码更新为以下代码
strtotime(date("Y-m-01 00:00:00")."Z"); // 用来获得本月的***天时间戳
至此问题解决!

PHP strtotime应用总结:

我们在开发过程中有时候被系统的支持而忽略了一些细节。就如本例在WINDOWS平台下是不会有这问题,但PHP strtotime应用还是要按规范的走会好些。以避免出现这类问题。

转载请说明出处
知优网 » PHP strtotime应用经验之谈(PHP strtotime)

发表评论

您需要后才能发表评论