开发者

DataContractJsonSerializer changing my date

开发者 https://www.devze.com 2023-01-13 20:31 出处:网络
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.

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 ((filterContex开发者_开发百科t.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?


Instead of using myTicks = myDate.getTime(); you probably want to use myTicks = myDate.UTC();

getTime() uses local time (based on the timezone where the browser is running). UTC() also gives you milliseconds since Jan 1, 1970, but it's Jan 1, 1970 UTC instead of local time. Microsoft's JSON serialization of dates uses the UTC measure.

Then you shouldn't need to do any server-side conversion.

0

精彩评论

暂无评论...
验证码 换一张
取 消