204

I am developing an API to expose some data using ASP.NET Web API.

In one of the API, the client wants us to expose the date in yyyy-MM-dd format. I don't want to change the global settings (e.g. GlobalConfiguration.Configuration.Formatters.JsonFormatter) for that since it is very specific to this client. And I do developing that in a solution for multiple clients.

One of the solution that I could think of is to create a custom JsonConverter and then put that to the property I need to do the custom formatting

e.g.

class ReturnObjectA 
{
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime ReturnDate { get;set;}
}

Just wondering if there is some other easy way of doing that.

Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90
Stay Foolish
  • 3,636
  • 3
  • 26
  • 30
  • 23
    For what it's worth, APIs are for computer readability, not user readability, so it's better to stick to a single specified date format, such as [ISO 8601](http://xkcd.com/1179/). If the client is directly displaying the API result to the user, or writing their own date parsing code for the API, then they're doing it wrong. Formatting a date for display should be left to the topmost UI layer. – MCattle Oct 15 '13 at 18:14
  • Create web API by using Visual Studio 2019, fixed by [Formatting DateTime in ASP.NET Core 3.0 using System.Text.Json](https://stackoverflow.com/questions/58102189/formatting-datetime-in-asp-net-core-3-0-using-system-text-json) – Stephen Feb 29 '20 at 00:26
  • I steer clear of sprinkling Json.NET specifics into my DTOs. Instead, I have DTO date properties you mention as `string`s that are formatted with a shared `const string` value. – HappyNomad Oct 21 '21 at 10:14

8 Answers8

217

You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter, then specify the date format in the constructor of the subclass. Apply the JsonConverter attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:

class CustomDateTimeConverter : IsoDateTimeConverter
{
    public CustomDateTimeConverter()
    {
        base.DateTimeFormat = "yyyy-MM-dd";
    }
}

If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK (as seen in the source code).

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • 2
    @Koen Zomers - The single quotes you removed from my date formats technically ARE correct, although they are not strictly necessary here. See _Literal String Delimiters_ in the [documentation for Custom Date and Time Format Strings](http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx). However, the format I quoted as the default format for the `IsonDateTimeConverter` was taken directly from the [Json.Net source code](http://json.codeplex.com/SourceControl/latest#trunk/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs); therefore I am reverting your edit on that. – Brian Rogers Jan 11 '14 at 19:51
  • it didn't work here with the quotes and it did without them, but if you say it should, I probably did something wrong. Sorry for the edit. – Koen Zomers Jan 24 '14 at 22:47
168

You could use this approach:

public class DateFormatConverter : IsoDateTimeConverter
{
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}

And use it this way:

class ReturnObjectA 
{
    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
    public DateTime ReturnDate { get;set;}
}

The DateTimeFormat string uses the .NET format string syntax described here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

John Smith
  • 7,243
  • 6
  • 49
  • 61
Keith Hill
  • 1,799
  • 1
  • 10
  • 4
  • 9
    This doesn't work for me - I get `'JsonConverterAttribute' does not contain a constructor that takes 2 arguments` – Tam Coton Jan 11 '18 at 10:49
  • 5
    This is the most flexible solution. If you get the following error : `'JsonConverterAttribute' does not contain a constructor that takes 2 arguments`, it means your version of json.net is too old. You need to update to the latest json.net version. – Florian Lavorel Aug 23 '18 at 09:41
  • 1
    Works for me. Any idea how I can remove the time? So only return 2020-02-12 for example with the T00:00:00 – Enrico Mar 24 '20 at 10:13
  • @Enrico Simple: `[JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd\"T:00:00:00\"")]` – Suncat2000 Apr 30 '21 at 18:52
  • 6
    @TamCoton one of the reasons seeing this error might be that you are referencing "System.Text.Json` instead of ."Newtonsoft.Json" in your file. At least that was the issue in my case. – Grigoryants Artem Nov 04 '21 at 22:41
74

It can also be done with an IsoDateTimeConverter instance, without changing global formatting settings:

string json = JsonConvert.SerializeObject(yourObject,
    new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });

This uses the JsonConvert.SerializeObject overload that takes a params JsonConverter[] argument.

Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
  • 7
    If you are serializing same class object in many places, then accepted answer is better than this – kgzdev Nov 01 '17 at 08:50
25

Also available using one of the serializer settings overloads:

var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });

Or

var json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });

Overloads taking a Type are also available.

Matt
  • 12,569
  • 4
  • 44
  • 42
13

There is another solution I've been using. Just create a string property and use it for json. This property wil return date properly formatted.

class JSonModel {
    ...

    [JsonIgnore]
    public DateTime MyDate { get; set; }

    [JsonProperty("date")]
    public string CustomDate {
        get { return MyDate.ToString("ddMMyyyy"); }
        // set { MyDate = DateTime.Parse(value); }
        set { MyDate = DateTime.ParseExact(value, "ddMMyyyy", null); }
    }

    ...
}

This way you don't have to create extra classes. Also, it allows you to create diferent data formats. e.g, you can easily create another Property for Hour using the same DateTime.

Antonio Rodríguez
  • 976
  • 2
  • 11
  • 25
10

With below converter

public class CustomDateTimeConverter : IsoDateTimeConverter
    {
        public CustomDateTimeConverter()
        {
            DateTimeFormat = "yyyy-MM-dd";
        }

        public CustomDateTimeConverter(string format)
        {
            DateTimeFormat = format;
        }
    }

Can use it with a default custom format

class ReturnObjectA 
{
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime ReturnDate { get;set;}
}

Or any specified format for a property

class ReturnObjectB 
{
    [JsonConverter(typeof(CustomDateTimeConverter), "dd MMM yy")]
    public DateTime ReturnDate { get;set;}
}
Ranga
  • 1,191
  • 12
  • 19
4
public static JsonSerializerSettings JsonSerializer { get; set; } = new JsonSerializerSettings()
        {
            DateFormatString= "yyyy-MM-dd HH:mm:ss",
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new LowercaseContractResolver()
        };

Hello,

I'm using this property when I need set JsonSerializerSettings

0

Some times decorating the json convert attribute will not work ,it will through exception saying that "2010-10-01" is valid date. To avoid this types i removed json convert attribute on the property and mentioned in the deserilizedObject method like below.

var addresss = JsonConvert.DeserializeObject<AddressHistory>(address, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" });
Muni Chittem
  • 988
  • 9
  • 17