简体   繁体   中英

Change DateTime format in JsonConvert.SerializeObject

I have a class called "Data" and it has "Name", "Date" and "Value". The "Date" Attribute is a DateTime value.

Now I have a List<Data> called "DataList" and I use the JsonConvert function on it like:

Newtonsoft.Json.JsonConvert.SerializeObject(DataList)

But now the Date is displayed like this YYYY-MM-DDTHH-mm-SS. Can I somehow Change this format before the JsonConvert is done?

If I understand correctly, what you want to do could be achieved by specifying the format as a parameter to the SerializeObject method.

Something like this:

var dt = DateTime.Now;
JsonSerializerSettings formatSettings = new JsonSerializerSettings
{
    DateFormatString = "dd/MM/yyyy"
};
var json = JsonConvert.SerializeObject(dt, formatSettings);

See this page for examples on how to do it: https://www.newtonsoft.com/json/help/html/DatesInJSON.htm

Don't do it.

This is not answering the question, because it is so bad, it should only be looked into as a last resort.

JSON, while being humanly readable, is an object serialisation standard to be used across systems. If you need to tweak the format, something is wrong.

The serialized date/time format is in ISO8601 form. It has been chosen so that every system that complies to that standard can interpreter the string correctly.

Strings like:

2018-09-20T09:23:46+00:00

are perfectly readable, causing no ambiguity, and will deserialize correctly by any system which uses the default settings.

Deviation from these kind of standards can give you serious issues while trying to maintain the system, cross device or cross culture.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM