Json. net Date Formatting Settings

  • 2021-11-01 02:48:42
  • OfStack

The default time format of Json. net is followed by T, which does not meet the business requirements of 1. Reset the default date format mode of JSON. NET. The code is as follows:


 /// <summary>
    /// Json.net Default conversion settings 
    /// </summary>
    private static void DefaultJsonConvertSetting()
    {
      JsonSerializerSettings setting = new JsonSerializerSettings();
      JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
      {
        // Date type default formatting 
        setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
        setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";

        // Null value processing 
        //setting.NullValueHandling = NullValueHandling.Ignore;

        return setting;
      });
    }

Let's look at the serialization format of Json. Net using attributes to define dates

If all the time fields of DateTime type in an entity class are processed into the Uniform 1 format, you can use the following methods:


IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
      timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
      JsonConvert.SerializeObject(stu, Newtonsoft.Json.Formatting.Indented, timeFormat);

If the format you need to return is not 1, for example, some need year, month and day, and some need year, month, day, hours, minutes and seconds, it cannot be controlled. You can solve this problem by defining attributes


public class student
  {
    public string Name { get; set; }
    public int Age { get; set; }
    [JsonConverter(typeof(DateFormat))]
    public DateTime BirthDay { get; set; }
    [JsonConverter(typeof(DateTimeFormat))]
    public DateTime CreateTime { get; set; }
  }
  public class DateFormat:IsoDateTimeConverter
  {
    public DateFormat()
    {
      base.DateTimeFormat = "yyyy-MM-dd";
    }
  }
  public class DateTimeFormat:IsoDateTimeConverter
  {
    public DateTimeFormat()
    {
      base.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    }
  }

Example demonstration:


student stu = new student()
       {
         Name = " Zhang 3",
         Age = ,
         BirthDay = new DateTime(, , ),
         CreateTime = DateTime.Now
       };
       string result = JsonConvert.SerializeObject(stu);

result = {"Name":" Zhang 3","Age":30,"BirthDay":"1986-07-16","CreateTime":"2016-01-16 23:13:34"}

This makes the granularity of control finer

Summarize

The above is the site to introduce you Json. net date formatting settings, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: