0

I have an application that is being built with Django and Django REST Framework. Users can add certain objects to the database and set expiry dates on them. Other users will retrieve those added items from the database and it will be displayed client-side. Both the users creating the objects and the users retrieving them could be in different places of the world.

I plan to store the datetimes in UTC format. How do I make sure that the datetime is in UTC format before storing and when a user tries to retrieve one of these items, it is correctly displayed in their Timezone?

What I am thinking

I am thinking that I should convert it to UTC (client-side) and save that to the database and then when a user retrieves that object I will return it in UTC (from the database) and change the time to the user's local time client-side. Is this a good approach?

NduJay
  • 760
  • 1
  • 10
  • 23
  • I am using django-rest-framework, so there is no way django can convert it in the template as there are no templates. Hence, why I am asking if I should return the data in UTC and convert it to their local timezone client-side. Thanks for the response! – NduJay Jan 18 '21 at 00:36
  • 1
    How do you know the desired timezone of the user? Are you storing that as a user preference (preferred) or relying on the client (i.e. browser) to tell you? – Kevin Christopher Henry Jan 18 '21 at 01:28
  • I am using flutter's `DateTime(datetime).toLocal()` functionality. Ideally, if it were a website, the browser would do the same ie. convert the UTC time to the browser's time – NduJay Jan 18 '21 at 01:43

1 Answers1

0

Briefly: if you're relying on the client knowing the correct timezone, then your solution is a good one.

A few notes:

  • Django doesn't require you to convert anything into UTC for storage, it will do that for you. That said, getting the UTC value on the client makes sense (and is really the only sane choice with the Flutter API).

  • Best practice in web applications is to allow the user to store their timezone as a user preference; that way, they have control over the timezone rather than being at the mercy of whatever computer and browser they happen to be using. That's probably less of a concern with mobile applications, where people can be assumed to be using their own device.

    If you were doing that, the best approach would be to have Django localize the time itself during serialization (something like this).

Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102