0

It seems I can't save "random" dates in my DB via Linq Query. I've followed this guide (JsonConvert.DeserializeObject could not convert string to DateTime when using non-us date formats) and the specific code is:

var format = "dd/MM/yyyy"; // your datetime format
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = format };

var ld = JsonConvert.DeserializeObject<Model>(jsonString, dateTimeConverter);

If my jsonString was {date: 12/5/2020} then it works, but for {date: 23/5/2020} or even {date: 30/5/2020}, it doesn't.

It feels very inconsistent as these are "random" dates that seem to work and not work, I can't even pinpoint why some are working and some are not.

I know this is a very vague question, but is there something I'm overlooking as to why these dates appear to not be saving?

Specific error:

summary response: Could not insert into database: Could not convert string to DateTime: 23/5/2020.

But if the date was 12/5/2020, saves successfully.

  • The ones that don't work have a day component greater than 12. Have you verified that the one that is "working" is actually saving with the day and month having correct values (and not reversed)? – pinkfloydx33 May 04 '20 at 05:38
  • 2
    Nothing random about it. The string representation format the code expects is `MM/dd/yyyy` and not `dd/MM/yyyy`. Note that all dates that can't be parsed has the "day" part (or, at least, what you expect as the "day" part) over 12. – Zohar Peled May 04 '20 at 05:39
  • ... Which is one more reason why you should always use ISO8601 when dealing with string representations of datetime values. – Zohar Peled May 04 '20 at 05:40
  • Thanks for the help, but regarding the MM/dd/yyyy, do you know why `var format = "dd/MM/yyyy"; ` doesn't "work" then? I thought by specifying the format as `dd/MM/yyyy` then the `MM/dd/yyyy` shouldn't be an issue since I'm telling the code what to expect? (Although, I might be misinterpreting what this means) –  May 04 '20 at 06:01
  • It doesn't work because SQL expects date in the other format. Why not using SQL-friendly date format `yyyy-MM-dd`? – aepot May 04 '20 at 06:23
  • I see, that makes sense - Thanks aepot. It's mainly a front-end issue to have it in the dd/MM/yyyy format, (if this wasn't here, I'd definitely do your suggestion)!. –  May 04 '20 at 06:32

0 Answers0