A user enters a date in a form, but when I pass a date through an AJAX json call, my date is getting changed by the DataContractJsonSerializer.
Here's my AJAX call:
function Save()
{
//Convert date to milliseconds from from 1/1/1970 - necessary for passing a date through JSON
var d = "09/01/2010 05:00";
myDate = new Date(d);
myTicks = myDate.getTime();
var message =
{
MessageID: $("#MessageID").val(),
MessageDate: '\/Date(' + myTicks + ')\/',
};
$.ajax({
url: "<%= Url.Action("SaveMessage") %>",
type: "POST",
dataType: "json",
data: $.toJSON(message),
contentType: "application/json; charset=utf-8",
success: function(result)
{
if (result && result.success)
{
//
}
}
});
}
Here's my serialization code:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json"))
{
var serializer = new DataContractJsonSerializer(RootType);
filterContext.ActionParameters[Param] = serializer.ReadObject(filterContext.HttpContext.Request.InputStream);
}
}
It's changing my dates to GMT. So if the user enters "09/01/2010 05:00", after serialization it comes out as "09/01/2010 09:00".
I was able to fix this in my local environment by using the function below, but it doesn't work in production. In my local environment, the server time is set to EST (11:00 AM). On production, the server time is set to GMT (3:00 PM).
Here is my conversion function:
public DateTime ConvertToLocal(DateTime dt)
{
int hours = TimeZoneInfo.Local.GetUtcOffset(dt).Hours;
DateTime dtGMT = dt.AddHours(Convert.ToDouble(hours));
return dtGMT;
}
This will correctly change my date from "09/01/2010 09:00 AM" back to "09/01/2010 05:00 AM" on my local environment, but on production it stays as "09/01/2010 09:00 AM".
It seems like in production, the DataContractJsonSerializer realizes that I'm browsing from EST, so it adds 4 hours. But since my production server is in GMT, my ConvertToLocal doesn't work, the Timezone offset in that function is 0 instead of -4.
What can I do to fix this?