I’m trying to figure out how to adapt this code below to offset any user’s timezone.
function now($format = 'Y-m-d H:i:s'){
return @date($format,mktime());
}
I used this below to adjust for my local time
function now($format = 'Y-m-d H:i:s'){
return @date($format,mktime() -3600);
}
but I need to adjust it dynamically to the user’s.
EDIT: I have the user define their timezone via a dropdown in a form, saving it to the DB, such as “America/Los_Angeles”.
Any ideas?
It will probably be a very good idea to use the DateTime objects that PHP provides. It promises to deal with time zones as well:
(Code from the doc page http://de3.php.net/manual/en/datetime.construct.php)
To get any information about the selected time zone, DateTimeZone offers access to the timezon database information via methods like
getTransitions()(you’ll get an array with the offsets for every time known, please see the example on http://de3.php.net/manual/en/datetimezone.gettransitions.php), andgetOffset()(which needs the time the offset is asked for, see http://de3.php.net/manual/en/datetimezone.getoffset.php).So basically there is no such thing as “the offset in seconds”, because this value changes depending on a) the time you are asking for, because stuff like daylight saving time will affect it over time, and b) the time you are asking it, because any changes to the timezone is affected by local legislation, not unchangeable natural law.
You are on the right way to store a universal time that can be transformed to local time when necessary, but I would suggest not trying to do it yourself, but to make use of what PHP has to offer. It’ll take you less time to code.