views:

34

answers:

2

Suppose now I've got the datetime to show like this:

2010-05-29 15:32:35

The the corresponding time zone can be get by date_default_timezone_get,

how do I output the result in the same time zone as user's browser so that users don't get confused?

A: 

You can pass UTC timestamps to the page and convert them with JavaScript. I used this trick once and was happy with the result. There is a constructor of JavaScript Date taking UTC timestamp. For UTC timestamp generation from PHP one may use gmmktime().

bobah
Can you illustrate? I'm not familiar with datetime functions at all...
@user198729 - Instead of generating '2010-05-01 14:37:00' into HTML page you generate something like (new Date('1272717420000')).toLocaleString()
bobah
+2  A: 

There is no reliable way to read the user's locale timezone settings from PHP or JavaScript.

In JavaScript you can read the offset between UTC and the time in the user's current timezone, but that doesn't give you a timezone name, so you're left either leaving the timezone identifier off (making the times completely ambiguous) or including it is an explicit offset like UTC+01:00, which is ugly, and still doesn't take care of changing timezones over different DST periods.

As bobah says, you can use toLocaleString() on a JavaScript Date to output it in the client's real desktop timezone. However, this way you get no control at all over the date formatting. For example on my machine Chrome outputs the unwieldy:

Sat May 29 2010 15:03:46 GMT+0200 (W. Europe Daylight Time)

Whereas Opera just coughs up:

29/05/2010 15:03:46

Which, as it doesn't state the timezone at all, is uselessly ambiguous. IE is similarly terse, and Safari states no timezone either. Firefox does for me on Linux, but not on Windows. Argh.

So if you need reliability the only way to handle timezones is to let the user manually choose one in their site settings, then convert from UTC to that timezone when you're producing a page for them. You can make a guess in JavaScript as to which the most likely of some common timezones it might be (see this question for strategies), but you can't guarantee you'll be right.

bobince