首页 > php框架 > PHP strtotime应用经验之谈

PHP strtotime应用经验之谈

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 werent 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应用还是要按规范的走会好些。以避免出现这类问题。
 


教程地址:http://www.phprm.com/frame/php1003981.html

欢迎转载!但请带上文章地址^^

标签:none

发表留言