Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

A function that converts the date of the johnson format to the Javascript object


May 08, 2021 JSON


Table of contents


The project encountered a string of dates in the jason format obtained from the background by jQuery, which needs to be converted to a JavaScript date object.

The code is as follows:
//转换json格式的日期(如:{ServerDatetime:"\/Date(1278930470649)\/"})为Javascript的日期对象 
function ConvertJSONDateToJSDateObject(JSONDateString) { 
var date = new Date(parseInt(JSONDateString.replace("/Date(", "").replace(")/", ""), 10)); 
return date; 
} 

3 ways to solve the jason date format problem

There are times in development when you need to return jason-formatted data from the server side, and in background code if data of the DateTime type is serialized using the tool class that came with the system, you get a very long number representing the date data, as follows:

The code is as follows:
//设置服务器响应的结果为纯文本格式
            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")}
            };
            //javascript序列化器
            JavaScriptSerializer jss=new JavaScriptSerializer();
           //序列化学生集合对象得到json字符
            string studentsJson=jss.Serialize(students);
           //将字符串响应到客户端
            context.Response.Write(studentsJson);
           context.Response.End();

The results are:

A function that converts the date of the johnson format to the Javascript object

Tom's birthday "2014-01-31" became 1391141532000, which is actually the number of milliseconds from January 1, 1970 to the present; 0/1000/60/60/24/365 s 44.11 years, 44 s 1970 s 2014, in this way can be derived from the year-and-month hours and milliseconds. This format is a viable representation but not a friendly format that ordinary people can understand, how can this format change?

Solution:

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

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 re-projects the object collection to convert the Wasday property into a new property, noting that the property can be renamed after the property changes, the property name can be the same;
Results:

A function that converts the date of the johnson format to the Javascript object


By this time the date format had become friendly, but in javascript it was just a string.

Method two:

In javascript, convert the strings in "Birthday": "/Date(1391141532000)"/" into date objects in javascript, and you can replace the non-numeric characters in Value, which is the corresponding key for Birthday, by replacing them To a number 1391141532000, and then instantiate a Date object, using 1391141532000 milliseconds as an argument, to get a date object in javascript, code as follows:

The code is as follows:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>json日期格式处理</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");
                    //使用正则表达式将生日属性中的非数字(\D)删除
                    //并把得到的毫秒数转换成数字类型
                    var birthdayMilliseconds = parseInt(obj.Birthday.replace(/\D/igm, ""));
                    //实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数
                    var birthday = new Date(birthdayMilliseconds);
                    $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents"); ;
                });
            });
        });
    </script>
</head>
<body>
    <h2>json日期格式处理</h2>
    <ul id="ulStudents">
    </ul>
</body>
</html>

Results:

A function that converts the date of the johnson format to the Javascript object


On the use of the positive rules / . T here are times when there will also be a situation of plus 86, only need to change the positive rules can also achieve the goal. In addition, if this problem of date formatting is repeated in your project, you can extend a javascript method with the following code:

The code is as follows:
$(function () {
            $.getJSON("getJson.ashx", function (students) {
                $.each(students, function (index, obj) {
                  $("<li/>").html(obj.Name).appendTo("#ulStudents");
                  //使用正则表达式将生日属性中的非数字(\D)删除
                    //并把得到的毫秒数转换成数字类型
                    var birthdayMilliseconds = parseInt(obj.Birthday.replace(/\D/igm, ""));
                  //实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数
                    var birthday = new Date(birthdayMilliseconds);
                  $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents");
                  $("<li/>").html(obj.Birthday.toDate()).appendTo("#ulStudents");
                });
            });
        });
        //在String对象中扩展一个toDate方法,可以根据要求完善
        String.prototype.toDate = function () {
            var dateMilliseconds;
            if (isNaN(this)) {
                //使用正则表达式将日期属性中的非数字(\D)删除
                dateMilliseconds =this.replace(/\D/igm, "");
            } else {
                dateMilliseconds=this;
            }
            //实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数
            return new Date(parseInt(dateMilliseconds));
        };

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

Method three:

You can select some third-party johnson tool classes, including some that have already addressed date format issues, and the common json serialization and anti-serialization tool libraries 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's an example of litjson as a tool class for serializing and anti-serializing json, as follows:

The code is as follows:
using System;
using System.Collections.Generic;
using System.Web;
using LitJson;
namespace JsonDate2
{
    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")}
            };
            //序列化学生集合对象得到json字符
            string studentsJson = JsonMapper.ToJson(students);
            //将字符串响应到客户端
            context.Response.Write(studentsJson);
            context.Response.End();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

The results are as follows:

A function that converts the date of the johnson format to the Javascript object

The date format at this time is basically correct, as 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:

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