39

Is there a simple way to configure JSON.NET so that some DateTime fields will be formatted without time and other DateTime fields will still be formatted with time?

Example:

{ firstName: 'John', lastName : 'Doe', birthday: '1965-09-23' }
trincot
  • 317,000
  • 35
  • 244
  • 286
RooSoft
  • 1,481
  • 2
  • 17
  • 32

3 Answers3

73

If you need this to only affect a particular field, create a converter type first:

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

and then add this attribute to whatever fields/properties you want this for:

[JsonConverter(typeof(OnlyDateConverter))]
Youssef Moussaoui
  • 12,187
  • 2
  • 41
  • 37
5

Try adding this line to configure your Web API:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
    new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd" });
Youssef Moussaoui
  • 12,187
  • 2
  • 41
  • 37
0

Yousesef's answer with the OnlyDateConverter is best. But here is one alternative:

private DateTime _birthday;
public string Birthday
{
    get { return _birthday.ToString("yyyy-MM-dd"); }
    set {
          _birthday = DateTime.ParseExact(value, "yyyy-MM-dd",
                                          CultureInfo.InvariantCulture);
        }
}

Advantage - You don't need to bind the Newtonsoft.Json library to your classes.

Disadvantage - The property is now exposed as a string anywhere you use it, which can cause it's own set of problems.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • I've considered that approach, but it may not be the best when computations could be involved between dates. Thanks anyways! – RooSoft May 03 '13 at 19:11