0

I have a WebAPI property like below.

[JsonConverter(typeof(DateFormatConverter), "mm-dd-yyyy")]
public DateTime? StartDate { get; set; }

And DateFormatConverter

public class DateFormatConverter : IsoDateTimeConverter
{
    /// <summary>
    /// Format of the date
    /// </summary>
    /// <param name="format"></param>
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}

if I pass following dates:
1- 10-20-2019
2- 2019-10-17T00:14:35.8384165-04:00

For example following should throw exception:

string stringDate = "\"2019-10-17T00:14:35.8384165-04:00\"";
DateTime deserializeObject = JsonConvert.DeserializeObject<DateTime>(stringDate, new DateFormatConverter("mm-dd-yyyy"));

both are getting parsed. But I would like to throw exception on second one. How can I handle this in DateFormatConverter?

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
  • Well maybe I am using the wrong base converter, but still my use case is the same. I will need exact parse from `mm-dd-yyyy` via Attribute. – Teoman shipahi Nov 01 '19 at 18:45
  • Your problem is that `JsonTextReader` has already recognized `"2019-10-17T00:14:35.8384165-04:00"` as a `DateTime` before your converter's `ReadJson()` is called. You need to set `DateParseHandling.None` at some higher level, e.g. as shown in [this answer](https://stackoverflow.com/a/40644970/3744182) to [How to prevent a single object property from being converted to a DateTime when it is a string](https://stackoverflow.com/q/40632820/3744182). Once you do you will get your exception, see https://dotnetfiddle.net/Y18NPk – dbc Nov 01 '19 at 18:58
  • 1
    In fact this looks like a duplicate of [How to prevent a single object property from being converted to a DateTime when it is a string](https://stackoverflow.com/q/40632820/3744182) and [Json.NET Disable the deserialization on DateTime](https://stackoverflow.com/q/11856694/3744182). Agree? – dbc Nov 01 '19 at 19:13
  • Thanks for the links. This will help, however when I do `StartDate = new DateTime(2019, 10, 20)` `JsonConvert.SerializeObject(obj, Formatting.Indented);` of instance of `RootObject` it serializes as ` "StartDate": "00-20-2019"` which is not expected. – Teoman shipahi Nov 01 '19 at 19:22
  • `"mm"` is *The minute, from 00 through 59.*. You want `"MM"`, *The month, from 01 through 12.* Demo: https://dotnetfiddle.net/dfLvZs – dbc Nov 01 '19 at 19:34
  • ahhgg, thanks for the correction. My bad. This works as expected now. Thanks a lot. And yes, we can mark this as duplicate. – Teoman shipahi Nov 01 '19 at 19:35

0 Answers0