使用date和time时候,有个缺点就是无法根据时区来调整时间,从PHP5.2开始可以使用datetime类进行构造,其构造方法需要两个参数,第一个是时间戳,另一个是时区(datetimezone)。
<code><span><span><?php </span><span>//可以从服务器获取时区信息</span><span>$timeZone</span> = ini_get(<span>'date.timezone'</span>); <span>$dtz</span> = <span>new</span> DateTimeZone(<span>$timeZone</span>); <span>//可以使用now表示当前时间</span><span>$dt</span> = <span>new</span> DateTime(<span>"now"</span>,<span>$dtz</span>); <span>//format进行格式化时间</span><span>echo</span><span>"data : "</span>.<span>$dt</span>->format(<span>"Y-m-d h:i:s"</span>);</span></span></code>
<code><span>//同样也可以使用diff()获得两个时间的时间差</span><span>$start_time</span><span>=</span><span>new</span> DateTime(<span>"2016-7-9 22:00:00"</span>,<span>$dtz</span>); <span>$difference</span><span>=</span><span>$start_time</span><span>-></span>diff(<span>$dt</span>); echo <span>$difference</span><span>-></span>format(<span>'%y-%m-%d %h:%i:%s'</span>); <span>//</span><span>data</span> : <span>2016</span><span>-</span><span>07</span><span>-</span><span>10</span><span>12</span>:<span>55</span>:<span>36</span><span>0</span><span>-</span><span>0</span><span>-</span><span>0</span><span>2</span>:<span>55</span>:<span>36</span></code>
以上就介绍了 PHP之time,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。