views:

271

answers:

3

On my Google App Engine application, i'm storing an auto-updated date/time in my model like that :

class MyModel(db.Model):
   date = db.DateTimeProperty(auto_now_add=True)

But, that date/time is the local time on server, according to it's time zone.

So, when I would like to display it on my web page, how may I format it according the client time zone ?

Also, how may I know on which time zone that google server is ?

+1  A: 

You can find out the server's timezone by asking for local and UTC time and seeing what the difference is. To find out the client timezone you need to have in your template a little bit of Javascript that will tell you e.g. in an AJAX exchange. To manipulate timezones once you've discovered the deltas I suggest pytz, pytz.sourceforge.net/ .

Alex Martelli
+3  A: 

With respect to the second part of your question:

Python time() returns UTC regardless of what time zone the server is in. timezone() and tzname() will give you, respectively, the offset to local time on the server and the name of the timezone and the DST timezone as a tuple. GAE uses Python 2.5.x as of the time of this posting; see the documentation for Python time functions here.

For the first part of the question:

You can either format the date with code on the server, or with code on the client.

  • If you format on the server, you can

    • Use the timezone of the requester's IP address
    • Require a user to register and give you a timezone, store it, and use the stored value
    • Use a (hidden?) field on the GET or POST so the client's desired timezone is part of the request
  • If you format on the client, you'll need to write a few lines of JavaScript. The procedure is something like "make a date from UTC using Date(utctime), then stuff it into the document." By default, JavaScript dates display as local time regardless of how they were initialized - awesome!

I recommend formatting on the client, because what's a webpage like without a bit of JavaScript? It's 2009! Marcelo has some examples.

Thomas L Holaday
+2  A: 

Ok, so thanks to Thomas L Holaday, I have to sent that UTC date to the client, for example using JSON :

json = '{"serverUTCDate":new Date("%s")}' % date.ctime()

And then, on the client side, add/remove the number of seconds according to the user time zone like that :

var localDate = serverUTCDate.getTime() - (new Date()).getTimezoneOffset()*60000;
paulgreg