Basic PHP timezones conversion

2019-09-06 12:21发布

问题:

I have looked at previous questions and nothing seems to fit what I require.

I am working on a scheduling system and now the client wants to add timezones.

So basically I need to be able to proform an action at a specific date and time.

Lets say someone chooses to have an alert at the following date/time:

25-12-2010 13:01:00 + / - their timezone

I need to be able to store this in mysql as an unix_timestamp, I have been looking at PHP's DateTime and DateTimeZone but this has confused me more.

I have looked at strtotime to also, i am just unsure of the best way to work out the date/time with the offset.

回答1:

Just to make sure we're on the same page, I just want to reiterate that a unix timestamp is merely the number of seconds since the "Unix Epoch" (January 1, 1970). Therefore simple math will work on unix timestamps.

There are two ways you could go about this; judging from your post you're confused as to which you'd like to use.

The first way would be the easiest (and most logical) way, and that is to store their offset (if you already have it, that is) and multiply that by 3600 (1 hour in seconds), and then add that value to the current unix timestamp to get their final time of running.

Another way to do it is to use the DateTime and DateTimeZone classes. How these two classes work, as shown here, is that you create two DateTimeZone objects, one with your timezone and one with theirs; create two DateTime objects with the first parameters being "now" and the second being the reference to the DateTimeZone objects above (respectively); and then call the getOffset method on your timezone object passing their timezone object as the first parameter, ultimately getting you the offset in seconds that can be added to the current unix timestamp to get the time that their job needs to run.

The second way seems much more complex for such an easy task if I do say so myself, so the first solution may suit your needs better. However, if you wish to have a more complete method, then using the DateTime and DateTimeZone would definitely be a possibility.

Quick note on strtotime: Strtotime is an easy opposite of the date() command, and won't be of any more use than a "tool" to achieve what you are looking for. It in and of itself will not convert or find offsets for you; it simply converts a formatted date and time into a unix timestamp.