开发者

API methodology. Working with timezones

I'm developing an API and I was just wondering if someone could advise on the following situation...

My webserver time has been set to UTC, PHP timezone has been set to use UTC. All times in my database are saved as unix timestamps, and each user is stored in the database along with their timezone.

Now my question is... should an API use the users stored timezone and adjust timestamps before sending them, or should it send the UTC timestamp and rely on the client asking for the timezone 开发者_如何学JAVAfrom the API adjusting before it's seen by the user?

How do other major APIs deal with timestamps?


I use the following hypothesis (in specification lingo):

APIs SHOULD serve UTC datetimes and the client/consumer SHOULD localize them properly if needed. The API SHOULD accept UTC datetimes, and MAY accept localized datetimes for setting.

I always serve UTC RFC3339 ISO timestamps on the following format: YYYY-MM-DD HH:MM:SSZ. A response from the API could look like this:

{
  'title' : 'Foo',
  'due_date': '2011-12-13 12:00:00Z'
}

While I at the same time allow the clients to specify aware datetimes. So I allow the following:

  1. http://api.example.com?title=Foo&due_date=2011-12-13 13:00:00+0100 -> converted to UTC and saved
  2. http://api.example-com?title=Foo&due_date=2011-12-13 12:00:00Z -> UTC

You can use the same hypothesis using UNIX timestamps (personally I don't want to use UNIX timestamps, since they do have a limited start (1970) and end date (2038)).

If you want to save which timezone was originally specified; you should definitely store that separately but alongside. Off the top of my head something like:

{
  'title' : 'Foo',
  'due_date' : {
                'utc': '2011-12-13 12:00:00Z',
                'converted_from' : '2011-12-13 13:00:00+0100'
  }
}

of if you prefer UNIX timestamps:

{
  'title' : 'Foo',
  'due_date' : {
               'utc': 1326456000,
               'original_offset' : 3600
  }
}                  


This is really a non-answer, but use what makes sense for your API.

Many services, for better or worse, will always communicate just a single time zone (mostly UTC). If that works for the application, then great.

However if the time zone has any meaning then it is clearly a mistake to not send along that information, either in a single piece (e.g. date string with time zone) or separated but alongside (e.g. date, time zone).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜