Heim  >  Artikel  >  Backend-Entwicklung  >  PHP strtotime应用经验之谈_PHP教程

PHP strtotime应用经验之谈_PHP教程

WBOY
WBOYOriginal
2016-07-15 13:34:37825Durchsuche

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


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445988.htmlTechArticlestrtotime(date(Y-m-01 00:00:00)); // 用来获得本月的第一天时间戳 在实际PHP strtotime应用中突然有一次碰到转换过来的时间比实际时间要慢了 8 小时...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn