I've been reading up on this topic for the past few hours, and I think I've got a handle on it, but I'd like some confirmation.
Situation
I want a user in, say, California to be able to post a comment that will be stored in MySQL. I then want a user in, say, Texas to be able to view the comment with the post date adjusted to his or her time zone.
Proposed Solution
Storing
date_default_timezone_set('UTC');
$Date = new DateTime();
to get a DateTime object with the current date and time in UTC.$Date->format()
to get the value to insert into the datetime type column in MySQL.Displaying
$Date = new DateTime($row['time']);
to instantiate a DateTime object with the stored UTC time.$Date->setTimezone(new DateTimeZone($userTimezone));
to adjust the UTC time to the user's timezone.$Date->format();
Is that the gist of what has to be done? Am I missing a better solution? Thanks for your help!
Use "zzz" instead of "ZZZ": "Z" is the symbol for an RFC822 time zone. DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Yes, Date. now() will give you the same UTC timestamp independent of your current timezone. Such a timestamp, rather a point in time, does not depend on timezones. The Java equivalent new Date() gives you the exact same thing.
When storing dates in the database, they should always be in UTC. If you are not familiar with what UTC is, it is a primary time standard that all the major timezones are based on. The major timezones are just offsets from UTC.
It can be made simpler still. Since you are using JavaScript then why not use JavaScript to adjust the time zone on the client as well?
Not only does this make things simpler but it also overcomes a problem with your model. If I registered my account in New York but travelling to Australia, I want to see the times as per the Australian time zone. In fact, using JavaScript you use can easily adjust the settings, making the design even more dynamic. Second, you can avoid the overhead of storing the user's time zone.
That said, if you want your design to degrade to non-JavaScript browsers then you are better off taking a full server side approach relying on HTTP cookies (as opposed to relying on JS to fetch cookies).
Your doing it all rights. Store all dates in UTC(GMT+0), retrieve them as such from the database and apply the user's offset.
Essentially, you've got it all covered from start to finish, there's really nothing to add, I don't think you can optimize it beyond what your doing already.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With