Parsing a JSON date info into a C# DateTime

前端 未结 4 1905
小鲜肉
小鲜肉 2021-01-11 19:11

I have a a WCF service that returns a CLR object. This object is defined as follows:

[DataContract]
public class Person
{
  [DataMember]
  public string Full         


        
相关标签:
4条回答
  • 2021-01-11 19:24

    The reason the date is in this weird format is that DateTime is a primitive in WCF. Unfortunately, there is no universally standardized format for serializing dates and times in JSON -- various frameworks use various string formats.

    The dilemma is that WCF needs to natively understand that a particular string over the wire is indeed a DateTime, not just another plain vanilla JSON string. Hence the strange format. As soon as DataContractJsonSerializer encounters a date starting with \/Date, it starts trying to parse it as a date.

    Now, to answer your question, when you are sending a DateTime over the wire, it depends on if you're using a web browser client, a Silverlight client, or a WCF client.

    A WCF client or a Silverlight 2+ client should NOT have problems with this -- they should auto-use the DataContractJsoNSerializer, and if they're not using it, you can plug in DCJS manually.

    If you are using a web client, you can include the .js file that ships with ASP. NET AJAX (I believe it is called MicrosoftAspNetAjax.js, or MicrosoftAjax.cs, though the name may have changed). Its deserialize function will auto-parse these dates as well.

    Hope that helps!

    0 讨论(0)
  • 2021-01-11 19:25

    This solved my problem

    using System.Web.Script.Serialization;
    
    
    //code
    JavaScriptSerializer json_serializer = new JavaScriptSerializer();
    DateTime ddate = json_serializer.Deserialize<DateTime>(@"""\/Date(1326038400000)\/""").ToLocalTime();
    
    0 讨论(0)
  • 2021-01-11 19:29

    Here are two options:

    You can use the Deserialize method from System.Web.Script.Serialization.JavaScriptSerializer (in System.Web.Extensions.dll).

    or you could use the ReadObject method from System.Runtime.Serialization.Json.DataContractJsonSerializer (in System.Runtime.Serialization.dll or in .NET 3.5 in System.ServiceModel.Web.dll).

    Make sure that your date is wrapped in quotes like:

    string dateString = @"""\/Date(1297367252340-0500)\/""";
    
    0 讨论(0)
  • 2021-01-11 19:33

    Well, lately I had to work on an Android Mobile (Xamarin Studio) app project where I was unable to use Newtonsoft Json (Json.NET) due to errors thrown during deployment to this specific device version (Android API 16 Version 4.2.1).

    Luckly I found an alternative library for json (System.Json). However this library does not have a way of casting JSON date to C# DateTime implicitly.

    I have created the following two functions for nullable date and date conversions from a string json date(i.e /Date(1389435240000+0000)/)

    The code can be improved but it does the job for now

    public static DateTime? ConvertToNallableDate(string date)
            {
    
                DateTime? val = null;
                /*          /Date(1389435240000+0000)/*/
                try{
                    if(!string.IsNullOrEmpty(date))
                    {
                        date = date.Replace ("/Date(", string.Empty).Replace (")/", string.Empty);
                        int pIndex = date.IndexOf ("+");
                        if(pIndex < 0) pIndex = date.IndexOf("-");
                        long millisec = 0;
                        date = date.Remove (pIndex);
                        long.TryParse (date, out millisec);
                        System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-GB");
                        DateTime newDate = DateTime.Parse ("1970,1,1", ci);
                        newDate = newDate.AddMilliseconds(millisec);
                        val = newDate == null ? (DateTime?)null : newDate;
    
                    }
                }catch {
                    val = null;
                }
                return val;
            }
    
            public static DateTime ConvertToDate(string date)
            {
    
                DateTime val = new DateTime();
                /*/Date(1389435240000+0000)/*/
                try{
                if(!string.IsNullOrEmpty(date))
                {
                    date = date.Replace ("/Date(", string.Empty).Replace (")/", string.Empty);
                    int pIndex = date.IndexOf ("+");
                    if(pIndex < 0) pIndex = date.IndexOf("-");
                    long millisec = 0;
                    date = date.Remove (pIndex);
                    long.TryParse (date, out millisec);
                    System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-GB");
                    DateTime newDate = DateTime.Parse ("1970,1,1", ci);
                    val = newDate.AddMilliseconds(millisec);
    
                }
                }catch {
                    val = new DateTime();
                }
                return val;
            }
    
    0 讨论(0)
提交回复
热议问题