Proper Way to Convert JSON Date to .NET DateTime During Deserialization

前端 未结 6 1265
暖寄归人
暖寄归人 2020-12-06 01:12

I have a javascript function that calls an MVC controller with JSON data:

var specsAsJson = JSON.stringify(specs);
$.post(\'/Home/Save\', { jsonData: specsAs         


        
相关标签:
6条回答
  • 2020-12-06 01:38

    I took @Bob Horn answer but it wasn't working for me. My REST service is using Javascritpt dates. I adapted the referred answer to an extension method.

    
    using System;
    
    namespace Mediatel.Framework
    {
        public static class JsonDate
        {
            public static DateTime ConvertToDateTime(this string jsonDate)
            {
                // JavaScript uses the unix epoch of 1/1/1970. Note, it's important to call ToLocalTime()
                // after doing the time conversion, otherwise we'd have to deal with daylight savings hooey.
                DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                Double milliseconds = Convert.ToDouble(jsonDate);
                DateTime dateTime = unixEpoch.AddMilliseconds(milliseconds).ToLocalTime();
    
                return dateTime;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 01:49

    One thing that catches people out quite often with converting between Javascript dates and various server-side languages is that although both sides may be able to understand a unix-style timestamp value, JS uses microsecond-precision timestamp, whereas in most other languages the default timestamp precision is to the second.

    In other words, 1347993132851 in Javascript needs to be divided by 1000 in order to be recognised as a unix timestamp in other languages.

    Alternatively, if your platform can accept formatted date strings, use the Javascript Date() object to convert a timestamp value into a formatted date to send to the server. Or even better, use a helper library such as Date.js or Moment.js.

    0 讨论(0)
  • 2020-12-06 01:52

    I found a simple answer. In my javascript, I was serializing the data using the JavaScriptSerializer. After much googling, I found this article that shows how to serialize using JsonConvert that causes a more .NET-friendly DateTime to be used.

    Old:

    var specs = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.JobSpecEquipment))
    

    Dates look like this: Date(1348017917565)

    New:

    var specs = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.JobSpecEquipment));
    

    Dates look like this: 2012-09-18T21:27:31.1285861-04:00

    So the problem was really how I was serializing in the first place. Once I used JsonConvert, deserialization on the back end simply worked.

    0 讨论(0)
  • 2020-12-06 01:55

    I found this piece of code on the internet. It worked like a charm for me...

    function customJSONstringify(obj) {
        return JSON.stringify(obj).replace(/\/Date/g, "\\\/Date").replace(/\)\//g, "\)\\\/")
    }
    
    0 讨论(0)
  • 2020-12-06 01:55

    JavaScript (well, EcmaScript) defines its DateTime string interchange format based on a simplification of the ISO-8601 standard.

    XML Schema defines its DateTime string interchange format based on ISO-8601 also.

    I have found it handy to use the .NET class System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDateTime to handle conversion from .NET DateTime values to XML formats and back.

    Since JavaScript is based on the same ISO-8601 standard, perhaps it will work for your JSON case as well.

    0 讨论(0)
  • 2020-12-06 01:59

    After receving the error

    /Date(1347992529530)/ is not a valid value for DateTime.

    using this replace worked for me.

    var data = ko.toJSON({ objext: obj});
    $.ajax({
        url: "/API/API.asmx/SaveObject",
        type: "POST",
        dataType: "json",
        contentType: "application/json; char-utf8;",
        data: data.replace(/\/Date/g, "\\\/Date").replace(/\)\//g, "\)\\\/"),
        success: function (r) {},
        error: function (e) {},
        complete: function () {}
    });
    
    0 讨论(0)
提交回复
热议问题