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

前端 未结 6 1268
暖寄归人
暖寄归人 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;
            }
        }
    }
    

提交回复
热议问题