Methods for JSON date format problems

Source: Internet
Author: User
Tags iso 8601 iso 8601 date iso 8601 date format

In development, it is sometimes necessary to return JSON-formatted data from the server side, and in the background code, if a datetime type of data is serialized using the system's own tool class, a long numeric representation of the date data is given, as follows:

           The result of setting the server response is plain text format            context. Response.ContentType = "Text/plain";           Student Object Collection            list<student> students = new list<student>            {                new Student () {Name = "Tom",                    Birthday =convert.todatetime ("2014-01-31 12:12:12")},                new Student () {Name = "Rose",                    Birthday = Convert.todatetime ("2014-01-10 11:12:12")},                new Student () {Name = "Mark",                    Birthday =convert.todatetime (" 2014-01-09 10:12:12 ")}            };            JavaScript serializer            JavaScriptSerializer jss=new JavaScriptSerializer ();           Serializes the student collection object to get the JSON character            string STUDENTSJSON=JSS. Serialize (students);           Responds the string to the client            context. Response.Write (Studentsjson);           Context. Response.End ();

The operating result is:

Where Tom's corresponding birthday "2014-01-31" became 1391141532000, which is actually the number of milliseconds since January 1, 1970; 1391141532000/1000/60/60/24/365=44.11 years, 44+1970= In 2014, this method can be used to derive the day of the month, minutes and milliseconds. This format is a workable representation but not a friendly format that ordinary people can understand, how to make this format change?

Workaround:

Method 1: convert the date format to the client by using the Select method or the LINQ expression on the server side:

Using system;using system.collections.generic;using system.web;using system.web.script.serialization;namespace    jsondate1{using System.Linq;        <summary>///Student class, Test with///</summary> public class Student {//<summary>        Name////</summary> public String name {get; set;}    <summary>//Birthdays///</summary> public DateTime Birthday {get; set;} }///<summary>///Returns the JSON character of the Student collection///</summary> public class Getjson:ihttphandler {p ublic void ProcessRequest (HttpContext context) {//sets the result of the server response to plain text format context.            Response.ContentType = "Text/plain"; Student Object Collection List<student> students = new List<student> {new Student () {Name = "Tom", Birthday =convert.todatetime ("2014-01-31 12:12:12")}, new Student () {Name = "Rose", Birthday =convert.t Odatetime ("2014-01-11:12:12 ")}, new Student () {Name =" Mark ", Birthday =convert.todatetime (" 2014-01-09 10:12:12 ")}            }; Use the Select method to re-project the collection of objects to convert the Birthday property to a new attribute//Note that the property will be renamed after the change and immediately execute var studentset = Studen Ts.                Select (p = = new {p.name, Birthday = p.birthday.tostring ("Yyyy-mm-dd")} ).            ToList ();            JavaScript serializer JavaScriptSerializer JSS = new JavaScriptSerializer (); Serializes the student collection object to get the JSON character string studentsjson = Jss.            Serialize (Studentset); Responds the string to the client context.            Response.Write (Studentsjson); Context.        Response.End ();            } public bool IsReusable {get {return false; }        }    }}

The Select method re-projects the collection of objects to convert the Birthday property to a new property, note that the property name can be the same after the property changes, you can use the Select method, or you can use a LINQ query expression or choose another way to achieve the same purpose This method can be used to eliminate the properties of the client in the collection, to achieve the purpose of simple optimization performance.

Operation Result:

The date format is now a friendly format, but in JavaScript it's just a string.

Method Two:

Converts a string from "Birthday": "\/date (1391141532000) \ \" In JavaScript to a Date object in JavaScript, You can delete the non-numeric word utilises substitution in the value corresponding to the birthday key to a number 1391141532000, then instantiate a Date object with 1391141532000 milliseconds as the argument. Get a Date object in JavaScript with the following code:

<! DOCTYPE html>

Operation Result:

The use of the regular/\D/IGM to replace all non-numeric purposes, \d represents non-numeric, IgM is a parameter, respectively, to ignore (ignore) case, multiple, global replacement, multi-line replacement (multi-line), there are some times there will be +86 of the situation, It is also possible to achieve the same goal by simply transforming the regular. Alternatively, if you have recurring problems with the date format that need to be handled in your project, you can extend a JavaScript method with the following code:

$ (function () {$.getjson ("Getjson.ashx", function (students) {$.each (Students, function (index , obj) {$ ("<li/>"). html (obj.                  Name). AppendTo ("#ulStudents"); Use regular expressions to remove the non-digit (\d) from the birthday attribute and convert the resulting number of milliseconds to the number type var birthdaymilliseconds = parseint (obj.                  Birthday.replace (/\d/igm, ""));                  Instantiate a new date format with a parameter var birthday = new Date (birthdaymilliseconds) using the number of milliseconds since January 1, 1970;                  $ ("<li/>"). HTML (birthday.tolocalestring ()). AppendTo ("#ulStudents"); $ ("<li/>"). html (obj.                Birthday.todate ()). AppendTo ("#ulStudents");            });        });        });            Extending a ToDate method in a String object, you can refine String.prototype.toDate = function () {var datemilliseconds as required; if (IsNaN (this)) {//Use regular expressions to remove non-numbers (\d) from the date attribute Datemilliseconds =this.replace (/\d/igm, "")            ;       } else {         Datemilliseconds=this;        }//Instantiate a new date format, using the number of milliseconds since January 1, 1970 to present the parameter return new date (parseint (datemilliseconds));         };

The method todate above is not necessarily reasonable or strong enough to be modified as needed.

Method Three:

You can select some third-party JSON tool classes, many of which have already been processed for date format problems, and the common JSON serialization and deserialization ToolPak are:

1.fastJSON.
2.json_checker.
3.Jayrock.
4.json.net-linq to Json.
5.LitJSON.
6.JSON for. NET.
7.JsonFx.
8.JSONSharp.
9.JsonExSerializer.
10.fluent-json
11.Manatee Json

Here is an example of a tool class that Litjson JSON as serialized and deserialized, with the following code:

Using system;using system.collections.generic;using system.web;using litjson;namespace JsonDate2{using System.Linq;        <summary>///Student class, Test with///</summary> public class Student {//<summary>        Name////</summary> public String name {get; set;}    <summary>//Birthdays///</summary> public DateTime Birthday {get; set;} }///<summary>///Returns the JSON character of the Student collection///</summary> public class Getjson:ihttphandler {p ublic void ProcessRequest (HttpContext context) {//sets the result of the server response to plain text format context.            Response.ContentType = "Text/plain"; Student Object Collection List<student> students = new List<student> {new Student () {Name = "Tom", Birthday =convert.todatetime ("2014-01-31 12:12:12")}, new Student () {Name = "Rose", Birthday =convert.t         Odatetime ("2014-01-10 11:12:12")},       New Student () {Name = "Mark", Birthday =convert.todatetime ("2014-01-09 10:12:12")}};            Serializes the student collection object to get the JSON character string Studentsjson = Jsonmapper.tojson (students); Responds the string to the client context.            Response.Write (Studentsjson); Context.        Response.End ();            } public bool IsReusable {get {return false; }        }    }}

The results of the operation are as follows:

The date format is basically correct, so long as the date is instantiated directly in JavaScript,

var date = new Date ("01/31/2014 12:12:12");
Alert (date.tolocalestring ());

The code for the client is as follows:

$ (function () {            $.getjson ("Getjson2.ashx", function (students) {                $.each (students, function (index, obj) {                    $ ("<li/>"). html (obj. Name). AppendTo ("#ulStudents");                    var birthday = new Date (obj. Birthday);                    $ ("<li/>"). HTML (birthday.tolocalestring ()). AppendTo ("#ulStudents");});            }        ); var date = new Date ("01/31/2014 12:12:12");        Alert (date.tolocalestring ());

Method Four:

This text sent to the blog has put forward their valuable comments, I did not consider the situation in the MVC, in fact, MVC can also use handler, so the difference is not very big, but MVC has a specific response to the server JSON action, the code is as follows:

Using system;using system.web.mvc;namespace jsondatemvc.controllers{public    class Homecontroller:controller    {public        jsonresult GetJson1 ()        {            //serializes the current date and time object and allows the client get request to            return Json (DateTime.Now, Jsonrequestbehavior.allowget);}}}    

Operation Result:

Download a Application/json file named GetJson1 with the content "\/date (1391418272884) \"

From the above, it seems that MVC does not specifically deal with date formats when serialized, we can decompile to see the source code:

The JSON method for the return call:

protected internal Jsonresult Json (object data, Jsonrequestbehavior behavior) {    return this. Json (data, NULL, NULL, behavior);}

This. Json method

Protected internal virtual Jsonresult Json (object data, String ContentType, Encoding contentencoding, Jsonrequestbehavior behavior) {    return new Jsonresult {data = data, ContentType = ContentType, contentencoding = Conte ntencoding, jsonrequestbehavior = behavior};}

Subclass of Jsonresult class ActionResult class, Executeresult method:

It is not difficult to see from the above code that Microsoft's Jsonresult class is still using the JavaScriptSerializer, so the returned result is the same as the method is not processed, to solve the problem we can derive a new class, overriding the Executeresult method, Using Json.NET to complete the serialization work, the code for the JsonResultPro.cs file is as follows:

namespace jsondatemvc.common{using System;    Using System.Web;    Using SYSTEM.WEB.MVC;    Using Newtonsoft.json;    Using Newtonsoft.Json.Converters; public class Jsonresultpro:jsonresult {public Jsonresultpro () {} public Jsonresultpro (object data, Json Requestbehavior behavior) {base.            data = data; Base.            Jsonrequestbehavior = behavior; This.        DateTimeFormat = "Yyyy-mm-dd hh:mm:ss"; } public Jsonresultpro (object data, String DateTimeFormat) {base.            data = data; Base.            Jsonrequestbehavior = Jsonrequestbehavior.allowget; This.        DateTimeFormat = DateTimeFormat;         }///<summary>///date format///</summary> public string datetimeformat{get; set;}            public override void Executeresult (ControllerContext context) {if (context = = null)            {throw new ArgumentNullException ("context"); }            if (this. Jsonrequestbehavior = = jsonrequestbehavior.denyget) && string. Equals (context. HttpContext.Request.HttpMethod, "GET", stringcomparison.ordinalignorecase)) {th            Row new InvalidOperationException ("mvcresources.jsonrequest_getnotallowed"); } httpresponsebase base2 = context.            Httpcontext.response; if (!string. IsNullOrEmpty (this. ContentType)) {Base2. ContentType = this.            ContentType; } else {Base2.            ContentType = "Application/json"; } if (this. ContentEncoding! = null) {Base2. ContentEncoding = this.            ContentEncoding; } if (this. Data! = null) {//Convert System.DateTime date format to ISO 8601 date format//iso 8601 (e.g. 2008-04-12t12                : 53Z) Isodatetimeconverter isodatetimeconverter=new isodatetimeconverter (); SetDate format Isodatetimeconverter.datetimeformat = DateTimeFormat; Serializes String Jsonresult = Jsonconvert.serializeobject (this.                Data,isodatetimeconverter); The corresponding result is base2.            Write (Jsonresult); }        }    }}

The code for using the Jsonresultpro action type above is as follows:

        Public Jsonresultpro GetJson2 ()        {            //serializes the current date and time object, and allows the client GET request, note that H is uppercase            return new Jsonresultpro ( DateTime.Now, "Yyyy-mm-dd hh:mm");        }

Operation Result:

"2014-02-03 18:10"

This allows you to set the date format exactly as you want, but notice that the format of the date is different, such as the time of the H if the uppercase represents a 24-hour system, or if the lowercase represents a 12-hour system. There are also a few questions to ask you:

1, through the reflector of the code to get a lot of changes, such as properties will become the form of Get_request () method, do not know if you have a better way.

2, in the anti-compiled code to use the resource file mvcresources.jsonrequest_getnotallowed, how to rewrite it can also be used?

Here are a few things to solve the problem of the date format after serialization in JSON, there should be a better and more perfect way, you are welcome to tell me. Because a lot of students asked me so I wrote this text, welcome criticism.

Sample code Download

MVC Sample code Download

Methods for JSON date format problems

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.