Sebastian
Sebastian

Reputation: 4811

Keep same Datetime format while reading from JSON in C#

I have a JSON content like this

"started_on": "2017-12-01",
"start_time": "2017-12-01T10:00:00+00:00",
"finish_time": "2017-12-01T11:00:00+00:00",

I want to read the start time and end time as a string in same format and i tried the below code for doing the same

 JObject _task = JObject.Parse(response_json);
 string _description = "\n start_time:" + (string)_task["start_time"];
 _description += "\n finish_time:" + (string)_task["finish_time"];

This reads from JSON correctly , but when i check the datetime format i can see this as like "12/01/2017" only. How can i keep the same format while doing the conversion and i want the text as it is in the JSON parameter

Upvotes: 0

Views: 402

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38777

You need to instruct JSON.NET to read them as strings:

var settings = new JsonSerializerSettings
{
    DateParseHandling = DateParseHandling.None
};
JObject _task = JsonConvert.DeserializeObject<JObject>(response_json, settings);

If you need to get some of the values as DateTime objects after they have all been read as strings, you can use this:

var dt = _task["property"].Value<DateTime>();

Although at this stage you may just want to create a class to represent your JSON:

public class MyTask
{
    public DateTime Property1 {get;set;} // property1 will be read as a DateTime
    public string Property2 {get;set;} // property2 will be read as a string
}
MyTask _task = JsonConvert.DeserializeObject<MyTask>(response_json);

Upvotes: 2

Related Questions