I have this data available for use:
Timezone of local time as integer: 8.75 (which is UTC+8.75)
1) 2012-09-04 03:15:03
2) 2012-09-03 18:30:03 (GMT)
3) 1346728503
4) 1346697003 (GMT)
Now, I’m wondering how to convert local time (1) to GMT one (2) (and vice versa) with consideration of all possible exceptions like summer times, 1970-2038 time limits etc.? Do they matter anyway?
PHP functions mainly don’t allow to specify timezone of local time to convert times – they take server’s local time which is not what I want (and I don’t want to alter it either). I can obviously subtract 8.75*60*60 from 1346728503 (3) but will this produce accurate value no matter what?
OK, first: PHP functions that accept timestamps don’t accept timezones because UNIX timestamps don’t know or care about time zones.
As I type, it is Monday, September 3rd, 2012 at 15:30:10 in the US Eastern time zone, which is currently observing Daylight Saving Time (“summer time”). In the UTC time zone, that corresponds to 19:30:10. Either way, it’s UNIX timestamp (
time_tvalue) 1,346,700,610. Depending upon your location on the Earth’s surface, your local time at that instant could fall anywhere in a 26-hour range, from 7:30:10 AM on September 3rd to 9:30:10 AM on September 4th (2012-09-03T07:30:10-12:00 to 2012-09-04T09:30:10+14:00). But no matter what your local label, the time in question is still 1,346,700,610 to UNIX and PHP.It looks like you attempted to calculate different
time_tvalues based on time zone, but that doesn’t compute. Time zone offsets are never applied totime_tvalues, which don’t change; they are only applied to the human-readable representation.If at all possible, do not attempt to do your own time zone conversions. The rules tend to change. Right now, local time for me is four hours earlier than UTC; in a couple months, it will be 5 hours earlier. Moreover, the rules for when that change happens are different this year than they were five years ago. So depending on the specific time stamp value I’m trying to convert, I have to apply different rules.
Use the library functions.
To convert a string representation of a time into a
time_tvalue, usestrtotime. If the string contains a time zone reference,strtotimewill do the conversion for you. If not, you can usedate_default_timezone_set, as Connie suggested, to tell PHP what timezone to use when interpreting the string.To convert a
time_tvalue back into a string, usedateto get “local” time (that is, time according to the time zone set withdate_default_timezone_set; you can ask PHP what that timezone is withdate_default_timezone_get), orgmdateto get UTC.