ASP.NET - Custom DateTime Converter for Json.NET to handle non-standard, empty string and null-value date formats

Custom DateTime Converter con Json.NET per gestire formati non-standard, empty string e valori null

Table of Contents

Handling DateTime string-serialized values is often annoying when you're working on a multi-language project, especially when you're working with string-based data formats such as XML, CSV, JSON and such. Luckily enough, almost every programming language/framework can provide some native method - or third-party tool - that can solve these issues for you: for .NET and JSON, the most widely used is the exceptional Json.NET by Newtonsoft library, providing unvaluable features such as the SerializeObject and DeserializeObject methods which allows the developer to serialize-deserialize classes of (almost) any kind with ease.

For an extensive guide to Json.NET you can browse the official documentation, full of useful and easy-to-understand samples. In this post, assuming you already know how to effectively use the tool, I'll talk about a specific DateTime scenario: how to properly de-serialize a JSON input string containing one or more DateTime string representations written in either non-standard format, empty string or null value.

The Problem

Let's take the following JSON:

Here's a perfect example of bad-generated JSON. I personally hate these kind of scenarios: not only we have two very different date formats (yyyyMMdd and yyyy/MM/dd), we also get some empty and null values instead of actual dates. Sadly, we can't be sure it won't be like that when you don't have control on the Json file itself. When it happens, let's see how we could de-serialize this Json in the following C# class:

As we can easily see, the MyDates class features 4 properties: two DateTime types and two DateTime? nullable types: if we were looking for a way to handle that badly-formatted Json, this can be a good start. However, should we try to use Json.NET to de-serialize the above Json like we did before, we would receive the following error:

ERROR: System.FormatException: String was not recognized as a valid DateTime.

The reason for that is easily understandable: those non-standard date formats and empty-string values are not supported by the default DateTimeConverter, which is expecting something like   Date(1198908717056)  instead.

The Solution

A very viable way to fix the issue is providing ourselves with a custom CustomDateTimeConverter, a tailor-made class where we can put all the rules we need to properly convert/de-serialize the various date and/or time formats we can possibly expect to receive, including non-standard formatsarbitrary formats, empty strings, null values and basically anything else.

Here's the CustomDateTimeConverter class that I'm using for most of my projects:

As soon as you place the above code within a CustomDateTimeConverter.cs and add it to your project, you can use the class in the following way:

As we can see by looking at the code, the class has been setup to accept the most common formats and to treat empty string values as they were null. It also provides an extended constructor that can accept a custom string, that can be used to handle any datetime format not included in the DefaultImputFormats array.

That's it for now: happy (de)serialization!


About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

2 Comments on “ASP.NET - Custom DateTime Converter for Json.NET to handle non-standard, empty string and null-value date formats”

  1. with this code how do you make the date format on the json be only like this:
    and not like this

    1. j.Donis,
      the class purpose is to read JSON date & datetime strings, not to “make” them. If you want to know how to output a yyyy-MM-dd date on a JSON string, you need to tell us the server-side language and/or the JSON library or module you’re using.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.