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.

3
  • 2
    Have you seen this: stackapps.com/questions/1175/… Commented Dec 27, 2011 at 16:46
  • See this question asked 19 hours ago stackoverflow.com/questions/8639315/… Commented Dec 27, 2011 at 17:08
  • @Babcock great link, thank you! If you want to post it as an answer I'll select it. Commented Dec 27, 2011 at 17:09

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.