日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > javascript >内容正文

javascript

[转]Newtonsoft JSON how to dynamically change the date format?

發(fā)布時(shí)間:2024/4/13 javascript 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [转]Newtonsoft JSON how to dynamically change the date format? 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文轉(zhuǎn)自:http://www.howtobuildsoftware.com/index.php/how-do/cg8K/jsonnet-newtonsoft-json-how-to-dynamically-change-the-date-format

I'm using Newtonsoft JSON Serializer and it's great and super fast but I'd like to do a bit more with it. I'm not sure it's possible as all the search I've done comes up to nothing. What I would like is to be able to truncate empty time, so when it's display 2014-01-01 00:00:00.000 I just want 2014-01-01 at the end, so basically cut the entire time when they're all zeros. For now I use this piece of code:

DataTable dt = loadData();// encode the string with Newton JSON.Net string output = JsonConvert.SerializeObject(dt,new JsonSerializerSettings{ReferenceLoopHandling = ReferenceLoopHandling.Ignore,Formatting = Newtonsoft.Json.Formatting.None,DateFormatString = "yyyy-MM-dd HH:mm:ss"});

Is there a way to format these dates without the time (only when they are all zeros) without affecting the performance?

?

Best How To :


????????????????

You can do this with a custom JsonConverter:

class CustomDateConverter : JsonConverter {public override bool CanConvert(Type objectType){return (objectType == typeof(DateTime));}public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer){DateTime date = (DateTime)value;string format = "yyyy-MM-dd HH:mm:ss";if (date.Hour == 0 && date.Minute == 0 && date.Second == 0 && date.Millisecond == 0){format = "yyyy-MM-dd";}writer.WriteValue(date.ToString(format));}public override bool CanRead{get { return false; }}public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer){throw new NotImplementedException();} }

Demo:

class Program {static void Main(string[] args){List<DateTime> dates = new List<DateTime>{DateTime.Now,DateTime.Today};JsonSerializerSettings settings = new JsonSerializerSettings{ReferenceLoopHandling = ReferenceLoopHandling.Ignore,Formatting = Newtonsoft.Json.Formatting.None,Converters = new List<JsonConverter> { new CustomDateConverter() }};string json = JsonConvert.SerializeObject(dates, settings);Console.WriteLine(json);} }

Output:

["2014-06-11 11:56:28","2014-06-11"]

?

總結(jié)

以上是生活随笔為你收集整理的[转]Newtonsoft JSON how to dynamically change the date format?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。