strtotime日期奇怪的结果 [英] strtotime date weird result

查看:87
本文介绍了strtotime日期奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下字符串日期: Fri September 02 2011 21:00:00 GMT + 0100(GMT Daylight Time)


$ b $在php中,如果我在上面做了一个strtotime,然后把它转换成一个字符串日期,似乎有一个小时。

  echo $ str_date,Vs,date(c,strtotime($ str_date)); 

产生:



Fri Sep 02 2011 21:00:00 GMT + 0100(GMT Daylight Time) Vs 2011-09-02T22:00:00 + 01:00



我意识到这是与夏令时相关的,但是如何补偿这个?

解决方案


我意识到这是关于夏令时,但是如何补偿这个?


不使用 date() strtotime(); DateTime 类是首选。

  $ str_date ='Fri Sep 02 2011 21:00:00 GMT + 0100'; 
$ datetime = new DateTime($ str_date);
echo $ datetime-> format('c'); // 2011-09-02T21:00:00 + 01:00

或程序风格

  $ str_date ='Fri Sep 02 2011 21:00:00 GMT + 0100'; 
echo date_format(date_create($ str_date),'c'); // 2011-09-02T21:00:00 + 01:00






Aside:如果你想继续使用 date() / strtotime()然后,作为其他答案和您自己的观察表明,您需要注意日期字符串和脚本中使用的时区。


Given the following string date: Fri Sep 02 2011 21:00:00 GMT+0100 (GMT Daylight Time)

in php if I do a strtotime on the above, and then convert it back to a string date, it seems to gain an hour.

echo $str_date,"  Vs ",date("c",strtotime($str_date));

Produces:

Fri Sep 02 2011 21:00:00 GMT+0100 (GMT Daylight Time) Vs 2011-09-02T22:00:00+01:00

I realise this is to do with daylight savings, but how does one compensate for this?

解决方案

I realise this is to do with daylight savings, but how does one compensate for this?

By not using date() and strtotime(); the DateTime class is preferred.

$str_date = 'Fri Sep 02 2011 21:00:00 GMT+0100';
$datetime = new DateTime($str_date);
echo $datetime->format('c'); // 2011-09-02T21:00:00+01:00

or in procedural style

$str_date = 'Fri Sep 02 2011 21:00:00 GMT+0100';
echo date_format(date_create($str_date), 'c'); // 2011-09-02T21:00:00+01:00


Aside: if you wish to still use date()/strtotime() then, as the other answers and your own observations show, you need to be careful with the time zones in use in the date string and your script.

这篇关于strtotime日期奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆