使用DST获取当前的星期开始/结束日期 [英] Get current week start/end date with DST
问题描述
我几个月来一直在使用以下代码,没有任何问题,以便获取当前的星期开始/结束日期(星期一/星期日):
I was using the following code for some months now without any issue in order to get the current week start/end date (Monday/Sunday):
date_default_timezone_set('Europe/Bucharest'); //this is the default in php.ini
$monday = strtotime('next Monday -1 week');
$monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
echo "Current week start/end date:<br>";
echo $this_week_sd = date("Y-m-d",$monday)."<br>";
echo $this_week_ed = date("Y-m-d",$sunday)."<br>";
//Expected result:
2018-10-29
2018-11-04
但是,从今天起,由于某种原因,这一天已被1天抵消:
However, as of Today this for some reason has been offset by 1 day:
//Actual incorrect result:
2018-10-28
2018-11-03
然后我想起了昨天,由于夏令时,时钟又回到了1小时,所以我决定将时区从欧洲/布加勒斯特更改为欧洲/伊斯坦布尔,相对于格林尼治标准时间+3小时:
Then I remembered that Yesterday the clock went back 1 hour due to DST, so I decided to change the timezone from Europe/Bucharest to Europe/Istanbul which still has a +3 hours advance against GMT:
date_default_timezone_set('Europe/Istanbul');
//Now the result is correct:
2018-10-29
2018-11-04
问题是,如何在当前代码中偏移DST,以便我可以将相对的星期日期保持在欧洲/布加勒斯特时区?任何指示或解释将不胜感激。谢谢。
Question is, how can I offset DST in the current code so that I could keep the relative week dates in accordance with Europe/Bucharest timezone? Any pointers or explanations would be appreciated. Thank you.
推荐答案
我知道有多种方法可以给猫换皮,但是在这种情况下,我很感兴趣
I am aware that there is more than one way to skin a cat, but in this case I was interested in how to fix my current code and more importantly to find out what's wrong with it.
谢谢大家的建议,尤其是@misorude指出了明显的缺陷在我的初始代码中,并非每天都有86400秒,在DST期间尤其如此。
Thank you all for your suggestions, especially to @misorude for pointing out the obvious flaw in my initial code, whereas "not every day has 86400 seconds", which is especially true during DST.
因此,这是使用相对的天而不是日期的更新的工作代码固定秒数:
So here's the updated working code using relative "days" instead of fixed seconds amount:
$monday = strtotime('next Monday -1 week');
$monday = date('w', $monday)==date('w') ? strtotime(date("Y-m-d",$monday)." +7 days") : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
echo "This week start/end date:<br>";
echo $this_week_sd = date("Y-m-d",$monday)."<br>";
echo $this_week_ed = date("Y-m-d",$sunday)."<br>";
//output:
This week start/end date:
2018-10-29
2018-11-04
再次感谢大家的投入。非常感谢!
Once again, thank you all for your inputs. Much appreciated!
这篇关于使用DST获取当前的星期开始/结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!