0

JsonConvert throws an error while converting string to DateTime.

I have set date formatter to fix this issue, but still the issue exists.Could not convert string to DateTime: 14-07-2019. Path 'CartDetails[0].LineItems[0].QuoteDate', line 1, position 371.

If I set the formatter I get "String was not recognized as a valid DateTime."

My JSON string has the following properties

And my object has the following properties

public DateTime QuoteDate { get; set; }
public DateTime LastUpdatedDate { get; set; }

"LastUpdatedDate": "01-01-0001"
"QuoteDate": "14-07-2019"

//var format = "dd-mm-yyyy'T'HH:mm:ssK";
//var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = format};
//var myObj= JsonConvert.DeserializeObject<MyObject>(checkOutBody,dateTimeConverter);
var myObj= JsonConvert.DeserializeObject<MyObject>(checkOutBody);

I expect my object to be parsed successfully

4
  • 1
    Well shouldn't the year be at the end of the date format string rather than the beginning, i.e. "dd-mm-yyyy"? Commented Jul 14, 2019 at 5:25
  • Also, rather than IsoDateTimeConverter use JsonSerializerSettings.DateFormatString. Commented Jul 14, 2019 at 5:26
  • 1
    I have set date formatter to fix this issue - where did you do that? in your code example you create an instance of such a formatter but never set it where it can affect anything Commented Jul 14, 2019 at 5:26
  • @SirRufo I have set it, and commented it back as it was not working. I have updated my question. Commented Jul 14, 2019 at 5:28

1 Answer 1

1

You need to tell JsonConvert.DeserializeObject to use the date format you are supplying.

The following examples below will pass to the same dates

string varf = "{\"LastUpdatedDate\": \"01-01-0001\",\"QuoteDate\": \"07-14-2019\"}";
string varf2 = "{\"LastUpdatedDate\": \"01-01-0001\",\"QuoteDate\": \"14-07-2019\"}";


var myObj = JsonConvert.DeserializeObject<MyObject>(varf);
var obj = JsonConvert.DeserializeObject<MyObject>(varf2, new IsoDateTimeConverter { DateTimeFormat = "dd-MM-yyyy" });

In example of myObj, there is no date format so it uses MM-dd-yyyy but example obj uses an explict dateformat

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

2 Comments

I have already set the formatter with dd-mm-yyyy'T'HH:mm:ssK settings.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.