Home Web Front-end JS Tutorial 3 ways to solve json date format problem_json

3 ways to solve json date format problem_json

May 16, 2016 pm 05:01 PM
json date format

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<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);
              / /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;

    /// <summary>
    /// 学生类,测试用
    /// </summary>
    public class Student
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public String Name { get; set; }

        /// <summary>
        /// 生日
        /// </summary>
        public DateTime Birthday { get; set; }
    }

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

            //使用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:

<!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) {
                                                                                                                               html(obj.Name).appendTo("#ulStudents");
                                                                                                                                                                                .replace(/ D/igm, "");

             $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents"); ;
                                                   }) ;
  </script>
</head>
<body>

  <h2>json date format processing</h2>

  <ul id="ulStudents ">
 </ul>
</body>
</html>



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 () {
                                                                      ("<li/>").html(obj.Name).appendTo("#ulStudents");

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

                    $("<li/>").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;

/// <summary>
/// Student class, used for testing
/// </summary>
public class Student
{
/// < summary>
/// Name

/// <summary>

/// <summary>
/// Return the json character of the student collection
/// </summary>
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<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")}
              };

            //序列化学生集合对象得到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) {
$> ("<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());

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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

Combination of golang WebSocket and JSON: realizing data transmission and parsing

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

What is the difference between MySQL5.7 and MySQL8.0?

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization tips for converting PHP arrays to JSON

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Nov 18, 2023 pm 01:59 PM

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Pandas usage tutorial: Quick start for reading JSON files

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

How do annotations in the Jackson library control JSON serialization and deserialization?

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development

Use PHP's json_encode() function to convert an array or object into a JSON string and format the output Use PHP's json_encode() function to convert an array or object into a JSON string and format the output Nov 03, 2023 pm 03:44 PM

Use PHP's json_encode() function to convert an array or object into a JSON string and format the output

See all articles