How to deserialize asp.net datetime as JSON datetime with client's timezone

ぃ、小莉子 提交于 2019-12-12 06:16:08

问题


I'm struggling with datetimes a bit. I'm using asp.net mvc api controllers, a microsoft sql server and AngularJS.

On some button click I'm sending a JSON formatted date to an api-controller. When I post 2015-11-31 00:00 and I look in Fiddler to see what's really posted, I see that the date is formatted as such: 2015-11-30T23:00:00.000Z. (2015-11-31 - 1 hour UTC+01:00 Amsterdam, Berlin, Ber....) This is perfect because there might be a difference between the timezone the sql server might be in and the client. (Or is it?)

The problem is though: When I get the date back from the sql server it doesn't take the client's time zone into account. When I read the DateTime object from the sql server and I return it JSON formatted, the date that's being displayed is: 2015-11-30T23:00:00.000Z. I want it to add 1 hour to be in the timezone where the client is.

My question is: What do I do to get it to keep the timezone in to account while deserializing the JSON string that comes back from my api-controller?

TIA!


回答1:


Problem turns out to be that when the object is being deserialized, the date property is not of type DateTime. It is of type string. Simply converting it to date by using new Date("2015-11-30T23:00:00.000Z") will do the trick.

I made filter for it:

.filter('from_gmt_to_local_date', [function () {
  return function (text) {
    return new Date(text);
  };
}])

Usage:

{{contract.StartDate | from_gmt_to_local_date | date:'dd-MM-yyyy'}}

Hope this helps anybody.



来源:https://stackoverflow.com/questions/30162443/how-to-deserialize-asp-net-datetime-as-json-datetime-with-clients-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!