2

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?

  • 1
    What is the value of `item.BIRTHDAY` and what is your `CurrentCulture` exactly? Debug your code and tell us. – Soner Gönül Sep 19 '19 at 07:18
  • Why use Newtonsoft Json instead of DateTime.Parse? – Matt Luccas Phaure Minet Sep 19 '19 at 07:19
  • @SonerGönül this is the value of item.Birthday - '20-09-1982 12:00:00'. Do I need to specify the currentculture? –  Sep 19 '19 at 07:20
  • @MattLuccasPhaureJensen I tried it and still getting the error –  Sep 19 '19 at 07:20
  • 1
    Possible duplicate of [Parse string to DateTime in C#](https://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp) – xdtTransform Sep 19 '19 at 07:25
  • Do you have some more code? What is `item`? – Stefan Sep 19 '19 at 07:37
  • @Stefan it is from my JSON file –  Sep 19 '19 at 07:42
  • 1
    The code posted is not your json reading code. If your classes have a DAteTime property and your json does not follow acual culture date format, you should [use a DateTimeConverter](https://blog.kulman.sk/custom-datetime-deserialization-with-json-net/) – Cleptus Sep 19 '19 at 07:46
  • @LawrenceAgulto Post the code where you parse the json to get the `item` – Stefan Sep 19 '19 at 07:52
  • @LawrenceAgulto Check my answer and feel free to comment it if you have any doubt. Long story short: Your error is not where you think it is. – Cleptus Sep 19 '19 at 13:18

2 Answers2

4

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

Cleptus
  • 3,446
  • 4
  • 28
  • 34
1

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.

  • 1
    Let me try this I will get back to you –  Sep 19 '19 at 07:24
  • @LawrenceAgulto The reason why you have to do it with ParseExact is because the json string does not follon .net current culture format. Check [this sample](https://rextester.com/live/HFJ90953) – Cleptus Sep 19 '19 at 07:29
  • @bradbury9 do I need to do this in all of my datetime when inserting? –  Sep 19 '19 at 07:31
  • To complement the answer: The call of `DateTime.Parse` uses a default formatting, which is most likely not the formatting that you use for your datetime value. The `ParseExact` will let you specify the format you want to use – Stefan Sep 19 '19 at 07:36
  • You are still getting the error because you may have posted the wrong code. You error is being raised before the posted code. – Cleptus Sep 19 '19 at 07:48
  • Are you getting a newtonsoft json exception while using the DateTime.ParseExact method? – Matt Luccas Phaure Minet Sep 19 '19 at 07:49
  • @MattLuccasPhaureJensen yes and the DateTimeParse also –  Sep 19 '19 at 07:56
  • In that case the error must be being thrown somewhere else because DateTime.Parse and DateTime.ParseExact wouldn’t throw a newtonsoft json exception. – Matt Luccas Phaure Minet Sep 19 '19 at 08:01
  • 1
    @MattLuccasPhaureJensen indeed, I have added an answer with a slightly better parsing (I do use TryParseExact) but also addressing the Newtonsoft exception. – Cleptus Sep 19 '19 at 08:17
  • Very nice answer :-) – Matt Luccas Phaure Minet Sep 19 '19 at 08:19