Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On GAE, how may I show a date according to right client TimeZone?

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 ?

like image 232
paulgreg Avatar asked May 15 '09 13:05

paulgreg


2 Answers

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.

like image 104
Thomas L Holaday Avatar answered Nov 14 '22 23:11

Thomas L Holaday


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;
like image 28
paulgreg Avatar answered Nov 15 '22 00:11

paulgreg