search
HomeWeb Front-endJS Tutorial3 ways to solve json date format problem_json

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
    {
    ///
    /// 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

    Statement
    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
    Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

    The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

    Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

    Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

    Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

    Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

    JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

    JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

    JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

    JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

    Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

    Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

    JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

    The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

    The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

    Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Hot Tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),