Newtonsoft.Json customize serialize dates

前端 未结 2 1818
闹比i
闹比i 2021-01-04 01:57

I am using Newtonsoft.Json for serializing my dates from C# to javscript what I want to do is have the json serializer use the current culture for formatting da

相关标签:
2条回答
  • 2021-01-04 02:14

    You'll want to set JsonSerializerSettings.DateFormatString to your desired format.

    var jsonSettings = new JsonSerializerSettings();
    jsonSettings.DateFormatString = "dd/MM/yyy hh:mm:ss";
    
    string json = JsonConvert.SerializeObject(someObject, jsonSettings);
    

    After that, you can either pass the settings object in each time you use the serializer, or follow the steps in the answer referenced by dbc. Although, you don't mention where this is running (ASP.NET, desktop, UWP, etc), so how you set it globally may differ.

    0 讨论(0)
  • 2021-01-04 02:38

    Yes you can use a Converter in the JsonSerializer settings.

    public class SpecialDateTimeConverter : DateTimeConverterBase
        {
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                throw new NotImplementedException();
            }
    
            public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
            {
                 writer.WriteValue(((DateTime)value).ToString("dd/MM/yyyy hh:mm:ss"));
            }
        }
    
        string convertedDateTime = JsonConvert.SerializeObject(DateTime.Now, Formatting.Indented, new SpecialDateTimeConverter());
    
    0 讨论(0)
提交回复
热议问题