2

I've written a REST endpoint with ASP.NET Web API 2 that receives dates. The backend system has no concept of UTC times or DST, the dates stored in the database are just the UK date and time.

The website feeding the endpoint, however, is including UTC offset values in the data sent to the end point (e.g. a date looks like "1939-01-08T00:00:00+01:00"). This happens when a summer date is entered in the winter or vice-versa (because of the adjustment for DST).

Is it possible for me to set the JSON deserializer to completely ignore those UTC offset values? I've looked at the docs here and the examples here and tried all of the different enum options, but none of them are giving me the behaviour I'm looking for.

tomRedox
  • 28,092
  • 24
  • 117
  • 154

1 Answers1

1

If the date parsing isn't working the way you want, you can turn it off and use a custom JsonConverter to handle the dates instead.

Here is a converter that should do the job:

class OffsetIgnoringDateConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(DateTime) || objectType == typeof(DateTime?));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string rawDate = (string)reader.Value;
        if (rawDate == null) return existingValue;
        if (rawDate.Length > 19) rawDate = rawDate.Substring(0, 19);
        DateTime date = DateTime.ParseExact(rawDate, "yyyy'-'MM'-'dd'T'HH':'mm':'ss", 
                                 CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal);
        return date;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To install this converter into the Web API pipeline, add the following to your Application_Start() method in Global.asax:

var config = GlobalConfiguration.Configuration;
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.DateParseHandling = DateParseHandling.None;
jsonSettings.Converters.Add(new OffsetIgnoringDateConverter());

Here is a demo (console app): https://dotnetfiddle.net/kt9pFl

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300