Reputation: 2111
I have a system that is used by multiple users and other systems across multiple time zones. I am hosting it on Azure. I want to save all dates in local time, not server time. I am able to do that by keeping track of each customer's local timezone and I am offsetting the dates before saving them in the database.
So far everything works well, however when the dates are sent back to the client's browser MVC thinks they are in UTC (this is the server time for all Azure VMs) and offsets the hours.
What is the most efficient way to prevent this? I tried setting the DateTimeKind to local, but this did not have the desired effect. The dates still got converted. I guess I could pass the dates as strings, but this seems like a hack. There must be a better way to do that.
Your suggestions are highly appreciated.
Upvotes: 1
Views: 1400
Reputation: 2111
Ok, so after couple of days of searching and testing I came up with a solution that solves the problem.
On the server:
public JsonResult GetModel()
{
EOListModel model = _repo.Getmodel();
return Json(JsonConvert.SerializeObject(model));
}
Couple of points here: - the method returns JsonResult - We serialize the model into a json string
On the client:
$.ajax({
type: "POST",
url: "/Controller/GetModel",
data: null
}).done(function (result) {
var m = JSON.parse(result);
...
});
result will be your json string and after parsing you will get your object with the dates intact.
I am not positive this is the best way to achieve this, but it works and has a minimal amount of code changes.
Thanks.
EDIT:
In the server method you also need to instruct JSON.NET not to append the timezone:
return Json(JsonConvert.SerializeObject(model, new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Unspecified }));
Otherwise Javascript or Moment will convert the date. See http://www.newtonsoft.com/json/help/html/SerializeDateTimeZoneHandling.htm for more details.
Upvotes: 2