4

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

"launch_date": 1250553600

How should I modify the following to include a custom DateTime parser that allows me to convert that number into a DateTime object?

JsonConvert.DeserializeObject<NTask>(json);

public sealed class NTask
{
    public DateTime launch_date { get; set; }
}

Alternatively I could use long and then parse it in another field but I'd rather avoid doing that, and have JsonConvert automatically parse it to DateTime through some converter.

bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • 2
    Have you seen this: http://stackapps.com/questions/1175/how-to-convert-unix-timestamp-to-net-datetime – M.Babcock Dec 27 '11 at 16:46
  • See this question asked 19 hours ago http://stackoverflow.com/questions/8639315/how-to-create-a-json-net-date-to-string-custom-converter/8639415#8639415 – L.B Dec 27 '11 at 17:08
  • @Babcock great link, thank you! If you want to post it as an answer I'll select it. – bevacqua Dec 27 '11 at 17:09

2 Answers2

3

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

Community
  • 1
  • 1
M.Babcock
  • 18,753
  • 6
  • 54
  • 84
1

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!

joe_coolish
  • 7,201
  • 13
  • 64
  • 111