Three ways to solve the json date format problem

  • 2020-03-30 01:36:09
  • OfStack

Sometimes in the development, it is necessary to return data in json format from the server side. In the background code, if there is data of DateTime type, it will get a long number to represent the date data after being serialized with the tools provided by the system, as shown below:


//Set the result of the server response to plain text
            context.Response.ContentType = "text/plain";
           //Student object set
            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();
           //Serialize the student collection object to get json characters
            string studentsJson=jss.Serialize(students);
           //Responds the string to the client
            context.Response.Write(studentsJson);
           context.Response.End();

The running result is:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201402/201402021905402.jpg "width = 660 >

Among them, Tom's corresponding birthday "2014-01-31" becomes 1391141532000, which is actually the number of milliseconds since January 1, 1970. 1391141532000/1000/60/60/24/365 = 44.11 years, 44 + 1970 = 2014, according to this approach can be concluded that split second, and millisecond when (date) (month) (year). This format is a viable representation but not a friendly format that ordinary people can understand. How do you change this format?

Solutions:

Method 1: on the server side, the date format is converted using the Select method or LINQ expression and sent to the client side:


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;
namespace JsonDate1
{
    using System.Linq;
    /// <summary>
    /// student class, for testing
    /// </summary>
    public class Student
    {
        /// <summary>
        /// name
        /// </summary>
        public String Name { get; set; }
        /// <summary>
        /// birthday
        /// </summary>
        public DateTime Birthday { get; set; }
    }
    /// <summary>
    /// returns the json character for the student collection
    /// </summary>
    public class GetJson : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //Set the result of the server response to plain text
            context.Response.ContentType = "text/plain";
            //Student object set
            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")}
            };
            //Use the Select method to re-project the collection of objects to convert the Birthday attribute to a new one
            //Note that the property is renamed after the change and executed immediately
            var studentSet =
                students.Select
                (
                p => new { p.Name, Birthday = p.Birthday.ToString("yyyy-mm-dd") }
                ).ToList();
            //Javascript serializer
            JavaScriptSerializer jss = new JavaScriptSerializer();
            //Serialize the student collection object to get json characters
            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 reprojects the collection of objects to convert the Birthday attribute to a new one. You can use the select method, you can use the LINQ query expression, or you can choose another way to achieve the same goal. This method can remove the different properties of the client in the collection and achieve the goal of simple performance optimization.

Operation results:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201402/201402021905403.png "width = 660 >

At this point the date format becomes friendly, but in javascript it's just a string.

Method 2:

In javascript, the string in "Birthday":"\/Date(1391141532000)\/" is converted into a Date object in javascript, and the non-numeric characters in the corresponding Value of Birthday Key can be deleted by substitution, to a number 1391141532000, and then instantiate a Date object, 1391141532000 milliseconds as the parameter, to get a Date object in javascript, the code is as follows:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>json Date format processing </title>
    <script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $.getJSON("getJson.ashx", function (students) {
                $.each(students, function (index, obj) {
                    $("<li/>").html(obj.Name).appendTo("#ulStudents");
                    //Use regular expressions to remove non-numeric (D) from the birthday property
                    //And convert the number of milliseconds to a numeric type
                    var birthdayMilliseconds = parseInt(obj.Birthday.replace(/D/igm, ""));
                    //Instantiates a new date format that takes the number of milliseconds from January 1, 1970 to the present as an argument
                    var birthday = new Date(birthdayMilliseconds);
                    $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents"); ;
                });
            });
        });
    </script>
</head>
<body>
    <h2>json Date format processing </h2>
    <ul id="ulStudents">
    </ul>
</body>
</html>

Operation results:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201402/201402021905404.jpg "width = 357 height = 310 >

The above method USES regular /\D/igm to replace all non-numbers. \D represents non-numbers and igm is a parameter, which respectively represents ignore case. Multiple and global substitutions; Multi-line substitution; Sometimes there will be a +86 case, you just need to transform the regular can also achieve the purpose. In addition, if the problem of dealing with date format occurs repeatedly in the project, you can extend a javascript method, the code is as follows:


$(function () {
            $.getJSON("getJson.ashx", function (students) {
                $.each(students, function (index, obj) {
                  $("<li/>").html(obj.Name).appendTo("#ulStudents");
                  //Use regular expressions to remove non-numeric (D) from the birthday property
                    //And convert the number of milliseconds to a numeric type
                    var birthdayMilliseconds = parseInt(obj.Birthday.replace(/D/igm, ""));
                  //Instantiates a new date format that takes the number of milliseconds from January 1, 1970 to the present as an argument
                    var birthday = new Date(birthdayMilliseconds);
                  $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents");
                  $("<li/>").html(obj.Birthday.toDate()).appendTo("#ulStudents");
                });
            });
        });
        //Extending a toDate method in a String object can be perfected on demand
        String.prototype.toDate = function () {
            var dateMilliseconds;
            if (isNaN(this)) {
                //Use regular expressions to remove non-numeric (D) from the date property
                dateMilliseconds =this.replace(/D/igm, "");
            } else {
                dateMilliseconds=this;
            }
            //Instantiates a new date format that takes the number of milliseconds from January 1, 1970 to the present as an argument
            return new Date(parseInt(dateMilliseconds));
        };

The above extended method toDate may not be reasonable or powerful enough to be modified as needed.

Method 3:

You can choose some third-party json tool classes, among which there are some json serialization and deserialization tool libraries that have handled the date format problem. The common json serialization and deserialization tool libraries are:

1. FastJSON.
2. JSON_checker.
3. Jayrock.
4.Json.NET - LINQ to JSON.
5. LitJSON.
6. JSON for the.net.
7. JsonFx.
8. JSONSharp.
9. JsonExSerializer.
10. Fluent - json
11. A Manatee Json

Here, litjson is used as a tool to serialize and deserialize json. The code is as follows:


using System;
using System.Collections.Generic;
using System.Web;
using LitJson;
namespace JsonDate2
{
    using System.Linq;
    /// <summary>
    /// student class, for testing
    /// </summary>
    public class Student
    {
        /// <summary>
        /// name
        /// </summary>
        public String Name { get; set; }
        /// <summary>
        /// birthday
        /// </summary>
        public DateTime Birthday { get; set; }
    }
    /// <summary>
    /// returns the json character for the student collection
    /// </summary>
    public class GetJson : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //Set the result of the server response to plain text
            context.Response.ContentType = "text/plain";
            //Student object set
            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")}
            };
            //Serialize the student collection object to get json characters
            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 operation results are as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201402/201402021905405.jpg "width = 612 height = 257 >

Now the date format is basically correct, just instantiate the date directly in javascript,

Var date = new date ("01/31/2014 12:12:12");
Alert (date. ToLocaleString ());

The client code 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());

There are three ways to solve the serialized date format problem in json, and you are welcome to let me know. Because many students ask me so I wrote this text, welcome the criticism to correct.

(link: http://xiazai.jb51.net/201402/other/jsonDate (jb51.net). Rar)


Related articles: