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

Suhel Patel
  • 278
  • 1
  • 12
Ram Venkat
  • 84
  • 1
  • 10
  • 1
    Well shouldn't the year be at the **end** of the date format string rather than the beginning, i.e. `"dd-mm-yyyy"`? – dbc Jul 14 '19 at 05:25
  • Also, rather than `IsoDateTimeConverter` use [`JsonSerializerSettings.DateFormatString`](https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonSerializerSettings_DateFormatString.htm). – dbc Jul 14 '19 at 05: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 – Sir Rufo Jul 14 '19 at 05:26
  • @SirRufo I have set it, and commented it back as it was not working. I have updated my question. – Ram Venkat Jul 14 '19 at 05:28

1 Answers1

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

Bosco
  • 1,536
  • 2
  • 13
  • 25
  • I have already set the formatter with dd-mm-yyyy'T'HH:mm:ssK settings. – Ram Venkat Jul 14 '19 at 05:44
  • 1
    look at possible date formats https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings – Bosco Jul 14 '19 at 05:48