I am saving all dates in my database as UTC. I now need to adjust to the client's local timezone.
Some background. I am using WebApi2 and I have an ASP.Net MVC5 web app consuming it. Eventually native apps will also consume the WebApi2 service.
Here is the method I use to get and render
protected async Task<T> GetAndParseApiResponse<T>(string url)
{
T model = default(T);
using (HttpClient client = GetHttpClient(SessionWrapper.AuthToken))
{
try
{
var response = await client.GetAsync(url)
.ConfigureAwait(false);
var formatter = new JsonMediaTypeFormatter
{
SerializerSettings = { TypeNameHandling = TypeNameHandling.Auto }
};
model = await response.Content.ReadAsAsync<T>(new List<MediaTypeFormatter> { formatter })
.ConfigureAwait(false);
}
catch (Exception ex)
{
throw new Exception("An exception occured performing GET at " + url, ex);
}
}
Some of the options I have come across that I am not too keen on include:
Convert at client size using moment and moment.timezone - I have tried this and it is unreliable because I had to use this code to compensate for DST which seems to work sometimes, and others it does not, so sometimes the time is correct times it is an hour forward, but in truth i'm not keen on handling it here so best I move on from this approach maybe:
var tz = jstz.determine(); var m = moment(value).tz(tz.name()); return m.add(m.isDST() ? 1 : 0, 'hours');
Manually adjust each DateTime object with the appropriate offset - Surely this is a last resort?! By this i mean every time a DateTime object is set to append the offset
Customise the JSON serializer so that DateTime are converted silently when returning a response from WebApi2 (or when receiving it). The reason I "think" this global approach would be the best is because I have DateTime objects in a lot of different models and are all currently being rendered as UTC at the client (ASP.Net MVC application). I need to adjust this DateTime before it is passed down as it is curently being deserialized with the UTC date (right or wrong that is what is happening)
I would love to implement option 3. I already have the client's local timezone as an offset (01:00, 02:00 etc). I'm just a bit confused to how to custom the serializer and where to do it.
Any help is greatly appreciated