-2

I am working with the you-tube API, which returns JSON data. The video published date is in this format: "publishedAt": "2017-04-30T18:18:41.000Z".

After deserializing the JSON object, I want to get the date from the published DateTime in C#.

How can I do it, and what is this format of DateTime?

noonand
  • 2,763
  • 4
  • 26
  • 51
Usf Noor
  • 217
  • 1
  • 4
  • 16
  • 3
    Possible duplicate of [How to parse and generate DateTime objects in ISO 8601 format](http://stackoverflow.com/questions/36313998/how-to-parse-and-generate-datetime-objects-in-iso-8601-format) – S. Buchegger May 02 '17 at 08:29
  • 2
    What about `DateTime.Parse("2017-04-30T18:18:41.000Z");`? – Pikoh May 02 '17 at 08:30
  • By creating a model with a DateTime property and deserializing into that model. What have you tried? – CodeCaster May 02 '17 at 08:34
  • @Pikoh Yes this works for me, thank you – Usf Noor May 02 '17 at 08:36
  • No, that is a bad suggestion, you shouldn't need to parse date strings manually. – CodeCaster May 02 '17 at 08:38
  • @CodeCaster well yes, the best way would be as you say deserializing to the correct model. But OP asks _After deserializing the json object, I want to get date from the published datetime in C#._ So if you want to parse it after deserializing, `DateTime.Parse` should do :) – Pikoh May 02 '17 at 08:40
  • @Pikoh there's answering what the OP asks, and understanding what they're trying to do. Those are commonly different. – CodeCaster May 02 '17 at 08:41
  • 2
    @CodeCaster well, you call it "understanding" but you could well call it "guessing". Maybe OP does not want to deserialize to a DateTime object, for any reason. Anyway,as I already told you, I also would go your way. That's why i didn't add it as an answer, but as a comment. – Pikoh May 02 '17 at 08:44
  • @CodeCaster I just need three things, video url, image and publish date, so i did't create model, I just create a class and loop through json deserialize object. – Usf Noor May 02 '17 at 08:50

1 Answers1

3

There's absolutely no need to manually parse a well-formatted ISO 8601 date.

Simply change the property on your model from string to DateTime:

public class VideoData
{
    [JsonProperty("publishedAt")]
    public DateTime PublishedAt { get; set; }
}

And then deserialize into that:

var model = JsonConvert.DeserializeObject<VideoData>(jsonString);

And Json.NET will handle the rest.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272