Search code examples
.netdatetimeasp.net-web-api

Web API: Converting all dates returned to a specific timezone?


I am using .Net Web API, and am returning datetimes in various models. These dates are coming from the database and are in UTC format.

I want all of these dates to be converted to a specific user's timezone (i.e. EST, CST, etc) before it gets serialized to JSON and returned back to the user. I don't want to manually convert each and every date every time it's retrieved from the database (it doesn't seem like DRY code). It also seems wrong to do the conversion in the database level as well.

Is there an easy way to apply some sort of filter that will automatically convert all dates returned to a specific timezone? For instance, something like the following:

[DateTime: EST Format]
class Event
   DateTime eventTime

If there's no easy way, how do you suggest I handle this scenario? Do the conversion in the UI layer? (what if there's a lot of dates displayed at once, we'll need to iterate through all of them and convert it)


Solution

  • There are a couple of ways you can do this. I would recommend implementing a custom serializer for your event object. This will allow you to serialize your datetime toLocal on the way out and toUtc on the way back.