user11695018
user11695018

Reputation:

Newtonsoft.Json.JsonReaderException: Could not convert string to DateTime:

I am trying ton insert some date into my local database. I am getting an error:

{Newtonsoft.Json.JsonReaderException: Could not convert string to DateTime: 20-09-1982 12:00:00. Path '[0].BIRTHDAY', line 1, position 71.

Here is my code:

var insertdata = new ClientIndividualTable
{
     COID = item.COID,
     CLIENTID = item.CLIENTID,
     BIRTHDAY = Convert.ToDateTime(item.BIRTHDAY)
};

await DefaultSettings.conn.InsertOrReplaceAsync(insertdata);

I also tried still getting the error:

DateTime.Parse(item.BIRTHDAY)

how can I fix and avoid this in the future?

Upvotes: 2

Views: 11078

Answers (2)

Cleptus
Cleptus

Reputation: 3541

Looks like your error is not in the line started with var insertdata = new ClientIndividualTable but some lines before that.

Your error is likely raising in a line similar to this one.

MyJsonClass item = JsonConvert.DeserializeObject<MyJsonClass>(fileText);

You must create a DateTime converter so Newtonsoft does know how to handle the custom format used. After that, you must decorate the class used to add a attribute to the DateTime property.

Sample JSON File:

{
    "COID" : "myCompanyId",
    "CLIENTID" : "myClientId",
    "BIRTHDAY" : "20-09-1982 12:00:00",
}

The class that matches the JSON structure:

public class MyJsonClass
{
    public string COID { get; set; }
    public string CLIENTID { get; set; }
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime? BIRTHDAY { get; set; }
}

And the JsonConverter would be similar to this.

public class CustomDateTimeConverter : DateTimeConverterBase
{
    private const string Format = "dd-MM-yyyy HH:mm:ss";

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((DateTime)value).ToString(Format));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.Value == null)
        {
            return null;
        }

        var s = reader.Value.ToString();
        DateTime result;
        if (DateTime.TryParseExact(s, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
        {
            return result;
        }

        return null;
    }
}

Note: I have based my answer in this blog post

Upvotes: 5

You could use DateTime.ParseExact like this

DateTime.ParseExact("20-09-1982 12:00:00", "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

ParseExact allows you to specify exactly the format you are storing no matter how many extra characters may be present.

Upvotes: 1

Related Questions