Home > Web Front-end > JS Tutorial > body text

3 ways to solve json date format problem_json

WBOY
Release: 2016-05-16 17:01:38
Original
1363 people have browsed it

During development, sometimes it is necessary to return data in json format from the server. If there is DateTime type data in the background code, use the system’s own tool class to serialize it and you will get a long number representing the date data, as follows Display:

Copy code The code is as follows:

//Set the server response result to plain text format
context.Response.ContentType = "text/plain";
//Student object collection
List students = new List
{
              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);
              / /Respond the string to the client
context.Response.Write(studentsJson);
context.Response.End();

The running result is:

Tom’s corresponding birthday "2014-01-31" has become 1391141532000, which is actually the number of milliseconds from January 1, 1970 to the present; 1391141532000/1000/60/60/24/365=44.11 years, 44 1970=2014, according to this method you can get the year, month, day, hour, minutes, seconds and milliseconds. This format is a feasible representation but not a friendly format that ordinary people can understand. How to change this format?

Solution:

Method 1: Convert the date format using the Select method or LINQ expression on the server side and send it to the client:

Copy code The code is as follows:

using System;
using System.Collections.Generic;
using System.Web;

using System.Web.Script.Serialization;

namespace JsonDate1
{
    using System.Linq;

    ///


    /// 学生类,测试用
    ///

    public class Student
    {
        ///
        /// 姓名
        ///

        public String Name { get; set; }

        ///


        /// 生日
        ///

        public DateTime Birthday { get; set; }
    }

    ///


    /// 返回学生集合的json字符
    ///

    public class GetJson : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //设置服务器响应的结果为纯文本格式
            context.Response.ContentType = "text/plain";
            //学生对象集合
            List students = new List
            {
                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")}
            };

            //使用Select方法重新投影对象集合将Birthday属性转换成一个新的属性
            //注意属性变化后要重新命名,并立即执行
            var studentSet =
                students.Select
                (
                p => new { p.Name, Birthday = p.Birthday.ToString("yyyy-mm-dd") }
                ).ToList();

            //javascript序列化器
            JavaScriptSerializer jss = new JavaScriptSerializer();
            //序列化学生集合对象得到json字符
            string studentsJson = jss.Serialize(studentSet);
            //将字符串响应到客户端
            context.Response.Write(studentsJson);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


The Select method reprojects the object collection and converts the Birthday attribute into a new attribute. Note that the attribute must be renamed after the attribute is changed. The attribute names can be the same; here you can use the select method or LINQ query expression, or you can choose something else. This method achieves the same purpose; this method can remove attributes that are not used by the client in the collection to achieve the purpose of simply optimizing performance.

Run result:

The date format at this time has become a friendly format, but in JavaScript this is just a string.

Method 2:

Convert the string in "Birthday":"/Date(1391141532000)/" into a date object in javascript. You can delete the non-numeric characters in the Value corresponding to the Birthday Key by replacing them. , to a number 1391141532000, and then instantiate a Date object, using 1391141532000 milliseconds as a parameter, to get a date object in javascript, the code is as follows:

Copy code The code is as follows:




json date format processing



json date format processing


     






Run result:



Use the regular /D/igm on
to replace all non-digits. D means non-digits, igm is a parameter, which respectively means ignore (ignore) upper and lower case; multiple, global (global) replacement; multi-line replacement ( multi-line); Sometimes there will be a situation of 86, and the purpose can be achieved by simply changing the regular expression. In addition, if the problem of needing to deal with date format occurs repeatedly in the project, you can extend a javascript method with the following code:

Copy code

The code is as follows:


$(function () {
                                                                      ("
  • ").html(obj.Name).appendTo("#ulStudents");

                                                                                                                                                                   place(/ D/igm, "");                 $("
  • ").html(birthday.toLocaleString()).appendTo("#ulStudents");

                        $("

  • ").html(obj .Birthday.toDate()).appendTo("#ulStudents");
                                              ;
    //Extend a toDate method in the String object, which can be improved according to requirements
    String.prototype.toDate = function () {
    var dateMilliseconds;

    if (isNaN(this)) {

                                                                                                                 this;
    } // instance a new date format, and the milliseconds from January 1, 1970 to the present are parameters
    Return New date

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


    Method three:

    You can choose some third-party json tool classes, many of which have already dealt with date format issues. Common json serialization and deserialization tool libraries include:

    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 litjson as an example of a tool class for serializing and deserializing json. The code is as follows:



    Copy code


    The code is as follows:


    using System;
    using System.Collections.Generic;
    using System.Web;

    using LitJson;

    namespace JsonDate2
    {
    using System.Linq;

    ///


    /// Student class, used for testing
    ///

    public class Student
    {
    /// < summary>
    /// Name

    ///

    ///


    /// Return the json character of the student collection
    ///

    public class GetJson: IHttpHandler
    {

    public void ProcessRequest (httpcontext context)

    {
    // Set the result of the server response as the pure text format
    context.Response.contenttype = "text/plain"; ;Student> students = new List
    {
    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")}
                  };

                //序列化学生集合对象得到json字符
                string studentsJson = JsonMapper.ToJson(students);
                //将字符串响应到客户端
                context.Response.Write(studentsJson);
    context.Response.End();
    }

    public bool IsReusable

    {
    get
    {
    return false;
    }
    }

    }

    }



    The running results are as follows:




    The date format at this time 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:


    Copy code

    The code is as follows:

    $ (fuins () {
    $ .getjson ("getjson2.ASHX", function (students) {
    $ .Each (Students, Function (INDEX, OBJ) {
    $> ("
  • ").html(obj.Name).appendTo("#ulStudents");
    var birthday = new Date(obj.Birthday);

    $("

  • ").html(birthday.toLocaleString()).appendTo("#ulStudents");
    } );
             });
            });

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

    alert(date.toLocaleString());

  • Here are three ways to solve the date format problem after serialization in json. There should be better and more complete methods. You are welcome to tell me. I wrote this because many students asked me. I welcome criticisms and corrections.

    Sample code download

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!