Dates without time in ASP.NET Web API JSON output

Is there an easy way to configure JSON.NET so that some DateTime fields are formatted without time and other DateTime fields still get formatted over time?

Example:

 { firstName: 'John', lastName : 'Doe', birthday: '1965-09-23' } 
+21
json datetime asp.net-web-api
May 01 '13 at 15:08
source share
3 answers

If you want this to affect only a specific field, first create a converter type:

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

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

 [JsonConverter(typeof(OnlyDateConverter))] 
+38
May 01 '13 at 19:15
source share

Try adding this line to configure your web API:

 config.Formatters.JsonFormatter.SerializerSettings.Converters.Add( new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd" }); 
+4
May 01 '13 at 18:39
source share

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

 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 do not need to link the Newtonsoft.Json library with your classes.

Disadvantage . The property now displays as a string anywhere you use it, which can cause your own set of problems.

0
May 01 '13 at 19:26
source share



All Articles