PHP - 使用日期找出夏令时 [英] PHP - using date to find out daylight savings time
问题描述
我想给date()一个日期,如果该日期是DST,则返回。在Windows 7框上通过xampp运行PHP 5.4.7。运行PHP 5.2.8的Linux操作系统返回0,无论我提供什么日期。
I want to give date() a date and have it return if that date is DST or not. Running PHP 5.4.7 via xampp on a windows 7 box. A linux box running PHP 5.2.8 returns 0 no matter what date I give it.
我的代码有什么问题?
echo date('I', strtotime('30-Mar-2013'));
# should return a 1 but returns 0
echo date('I', strtotime('30-Mar-2013 America/Los_Angeles'))."<br>"; # returns 0
echo date('I', strtotime('31-Mar-2013 America/Los_Angeles'))."<br>"; # returns 1
DST之间的切换应在2013年3月9日至2013年3月10日。
The switch between DST should be between 9-Mar-2013 - 10-Mar-2013.
此时,问题是为什么我的PHP代码不返回1。
At this point, the question is, why doesn't my PHP code return 1.
推荐答案
您不能使用 strtotime
,因为它创建了一个UTC时间戳记,可以删除时区信息。相反,只需使用 DateTime
You can't use strtotime
because it creates a UTC timestamp, which removes the timezone information. Instead, just use DateTime
$date = new DateTime('30-Mar-2013 America/Los_Angeles');
echo $date->format('I');
# 1
$date = new DateTime('31-Mar-2013 America/Los_Angeles');
echo $date->format('I');
# 1
$date = new DateTime('09-Mar-2013 America/Los_Angeles');
echo $date->format('I');
# 0
$date = new DateTime('10-Mar-2013 America/Los_Angeles');
echo $date->format('I');
# 0
请注意,最后一个DST仍然为0?这是因为转换发生在凌晨2:00:
Notice that the DST is still 0 on that last one? That's because the transition happens at 2:00 AM:
$date = new DateTime('10-Mar-2013 01:00 America/Los_Angeles');
echo $date->format('I');
# 0
$date = new DateTime('10-Mar-2013 02:00 America/Los_Angeles');
echo $date->format('I');
# 1
这是一个弹跳式转换,时钟从2:00至3:00。
This is a "spring-forward" transition, where the clock jumps from 2:00 to 3:00.
在回退过渡期间小心模糊,时钟从2:00返回到1:00
Beware of ambiguity during fall-back transitions, where the clock jumps from 2:00 back to 1:00
$date = new DateTime('3-Nov-2013 01:00 America/Los_Angeles');
echo $date->format('I');
# 1
有两个1:00 AM,这是第一个。这是不明确的,因为我们可能意味着第二个,而不是代表。
There are two 1:00 AMs, and this is taking the first one. It is ambiguous, because we might have meant the second one, and that is not represented.
人们会认为PHP将允许以下任一项:
One would think that PHP would allow either of the following:
new DateTime('3-Nov-2013 01:00 -0700 America/Los_Angeles') #PDT
new DateTime('3-Nov-2013 01:00 -0800 America/Los_Angeles') #PST
但这些不我测试时似乎工作。我也尝试过ISO格式的日期。任何人都知道如何正确区分PHP中的模糊值?如果是,请在评论中编辑或更新。谢谢。
But these don't seem to work when I tested. I also tried ISO format dates. Anyone know how to properly distinguish ambiguous values in PHP? If so, please edit or update in comments. Thanks.
这篇关于PHP - 使用日期找出夏令时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!