Parse custom date format using JSON.Net

后端 未结 2 1317
野趣味
野趣味 2021-01-13 21:27

I\'m receiving a JSON date in the following format:

\"launch_date\": 1250553600

How should I modify the following to include a custom DateT

相关标签:
2条回答
  • 2021-01-13 21:57

    Here is some code to do that:

    // This is an example of a UNIX timestamp for the date/time 11-04-2005 09:25.    
    double timestamp = 1113211532;
    
    // First make a System.DateTime equivalent to the UNIX Epoch.    
    System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
    
    // Add the number of seconds in UNIX timestamp to be converted.    
    dateTime = dateTime.AddSeconds(timestamp);
    

    For your code:

        JsonConvert.DeserializeObject<NTask>(json);  
    
        public sealed class NTask
        {
            public DateTime launch_date { get; set; }
    
            public void SetLaunchDate(int timestamp)
            {
                // First make a System.DateTime equivalent to the UNIX Epoch.    
                var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    
                // Add the number of seconds in UNIX timestamp to be converted.    
                launch_date = dateTime.AddSeconds(timestamp);
            }
        }
    

    Then when you are Deserializing the JSON, check to see if the launch_date is of type int or DateTime and switch how you set the object based on the type!

    0 讨论(0)
  • 2021-01-13 22:06

    You're going to want to use a JSONConverter to help manage the translation. See this stackapps answer for more detail.

    0 讨论(0)
提交回复
热议问题