PHP Daylight savings conundrum

喜你入骨 提交于 2019-11-29 10:16:38

Have you tried looking at DateTimeZone::getTransitions() ?

http://www.php.net/manual/en/datetimezone.gettransitions.php

In particular use the [offset] and [isdst] properties.

  • When they save the time, find the first transition before the current date that is NOT DST. (Typically one of the two values in the past year). Convert using the offset of the non-DST period
  • When retrieving the value and you are currently in a DST period use the offset of a non-DST period to translate the time, not the current offset.

Taking your EST example, in August even though you are in EDT, you save values using the EST conversion of -5.

When pulling the value back out if they view that value in January you add 5, and if you are in August you add 4.

This will work for 95% of cases I'm assuming that the switches are consistent. If Eastern decided to merge with Central, you could have transitions that run –5/–4/–5/–4/–5/–5/–6/–5/–6/–6 and that would mess things up.

There's no magic bullet for this one. I don't know the details of your app structure, you may just have to try adding 3 hours to the midnight of whatever day you are on so that any recurring daily appointment is stored as a time only.

This is a complicated problem. I've learned the hard way that not every day is 86,400 seconds long.

When working on a calendar application of sorts, I made a design decision early on that saved me a lot of hassle. That is, every instance of an event has an entry in the database.

One table was for all of the event information (title, description, etc.). Another table held a timestamp for each instance of that event. When someone scheduled a repeating event (say 3:00PM every Wednesday), I would insert an instance at 3:00PM in their timezone (which is actually stored as UTC) every Wednesday. Now, events in theory can repeat forever. I decided that it was much simpler to put a reasonable limit (say 50 or 100 years) on the repetition than it would be to have to calculate all of the dates of an event on the fly. To the user, it looks like the event goes on forever, but in the database it doesn't. Even if you have an event scheduled every day for 100 years, that's only 36,500 records in a very narrow table.

With this approach you have to consider exceptions. Sometimes people will change the details of one instance of an event. In those cases, I simply created another event and copied over the relevant details... since it is effectively a separate event. If you wanted to tie them all together with a group ID, you could. Changing individual scheduling of the event is easy since there is a separate row for each instance.

I recommend this approach for most scenarios like this. It saved a lot of hassle for me to be able to rely on a database for all the heavy lifting, and also solves your timezone problem at the same time.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!