How to accept datetime data and generate long or string data?

Source: Internet
Author: User

Reference Newtonsoft. Json. dll first. Then, see the code:

View Code

Public class JsonConverterStrAndLongToDate: JsonConverter {public override bool CanConvert (Type objectType) {return objectType = typeof (DateTime);} public override object ReadJson (JsonReader reader, Type objectType, object existingValue, jsonSerializer serializer) {if (reader. tokenType = JsonToken. string) {return From1970MilinSeconds (Int64.Parse (string) reader. value);} else if (reader. tokenType = JsonToken. integer) {double s = 5/3; return From1970MilinSeconds (Int64) reader. value);} throw new JsonReaderException (string. format ("Unexcepted token {0}", reader. tokenType);} public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) {var longValue = (long) (DateTime) value ). addHours (-8)-new DateTime (1970, 1, 1 )). totalMilliseconds; writer. writeValue (longValue );} /// <summary> /// convert the millisecond value to the datetime type /// </summary> /// <param name = "datetime"> </param> /// <returns> </returns> private DateTime From1970MilinSeconds (long datetime) {datetime * = 10000; var ts = new TimeSpan (datetime); var dt = new DateTime (1970, 1, 1); dt = dt. add (ts); // dt = dt. addHours (8); return Convert. toDateTime (dt. toString ());}}

Finally, during serialization

View Code

 return new ContentResult()                         {                             Content = JsonConvert.SerializeObject(result),                             ContentType = "application/json"                         };

Success!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.