Dates without time in ASP.NET Web API's JSON output

前端 未结 3 665
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 18:12

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

3条回答
  •  失恋的感觉
    2020-12-01 18:35

    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.

提交回复
热议问题