2

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?

jonthoughtit
  • 165
  • 1
  • 17
  • use a bit of JS to get the correct user offset ? like in this previous question : http://stackoverflow.com/questions/1091372/getting-the-clients-timezone-in-javascript – MimiEAM Oct 09 '12 at 22:56
  • I just edited it. I actually have the user input their timezone. – jonthoughtit Oct 09 '12 at 23:00

1 Answers1

1

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:

// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

(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), and getOffset() (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.

Sven
  • 69,403
  • 10
  • 107
  • 109
  • This works for me. I changed it to the following to work with what I needed: `function nowUnix($user_timezone){ $date = new DateTime(null, new DateTimeZone($user_timezone)); $newdate = $date->format('Y-m-d H:i:s'); $timestamp = strtotime($newdate); return $timestamp; }` – jonthoughtit Oct 11 '12 at 00:50
  • The DateTime object has a very convenient method `getTimestamp()` that gives you the unix timestamp - there is no need to output the time into a string and the parse it into a timestamp again. – Sven Oct 11 '12 at 07:57