Four solutions to the problem of JSON date format (super detailed)

Time:2021-12-28

Sometimes it is necessary to return JSON format data from the server during development. If there is datetime type data in the background code, a long number will be obtained to represent the date data after serialization using the tool class provided by the system, as shown below:

//Set the result of the server response 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 the JSON character
 string studentsJson=jss.Serialize(students);
 //Response string to client
 context.Response.Write(studentsJson);
 context.Response.End();

The operation result is:

Tom’s birthday “2014-01-31” has become 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 method, the hours, minutes, seconds and milliseconds of month, month and day can be obtained. This format is a feasible representation, but it is not a friendly format that ordinary people can understand. How to change this format?

terms of settlement:

Method 1: on the server side, convert the date format using the select method or LINQ expression and send it to the client:

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 of the student set
 /// </summary>
 public class GetJson : IHttpHandler
 {
 public void ProcessRequest(HttpContext context)
 {
 //Set the result of the server response 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")}
 };
 //Use the select method to re project the object collection to convert the birthday property to a new property
 //Note that after the attribute changes, rename it and execute it 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 the JSON character
 string studentsJson = jss.Serialize(studentSet);
 //Response string to client
 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 name should be renamed after the attribute changes, and the attribute name can be the same; Here, you can use the select method, LINQ query expression, or other methods to achieve the same purpose; This method can eliminate the attributes not used by the client in the collection, so as to simply optimize the performance.

Operation results:

At this time, the date format has become friendly, but in JavaScript, it is just a string.

Method 2:

In JavaScript, convert the string in “birthday”: “\ / date (1391141532000) \ /” into a date object in JavaScript. You can replace the non numeric characters in the value corresponding to the birthday key to a number 1391141532000, and then instantiate a date object. Take 1391141532000 milliseconds as a parameter to obtain 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");
 //Delete non numeric (\ d) in birthday attribute using regular expression
 //And convert the number of milliseconds to a number type
 var birthdayMilliseconds = parseInt(obj.Birthday.replace(/\D/igm, ""));
 //Instantiate a new date format, using the number of milliseconds since January 1, 1970 as the parameter
 var birthday = new Date(birthdayMilliseconds);
 $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents"); ;
 });
 });
 });
 </script>
</head>
<body>
 <h2>JSON date format processing</h2>
 <ul>
 </ul>
</body>
</html>

Operation results:

Use regular / \ D / IgM on to replace all non numbers, \ D means non numbers, IgM is a parameter, and respectively means ignore case; Multiple and global replacements; Multi line replacement; In some cases, there will be + 86, which can also be achieved by transforming regularization. In addition, if the problem of dealing with date format occurs repeatedly in the project, you can extend a JavaScript method, and the code is as follows:

$(function () {
 $.getJSON("getJson.ashx", function (students) {
 $.each(students, function (index, obj) {
 $("<li/>").html(obj.Name).appendTo("#ulStudents");
 //Delete non numeric (\ d) in birthday attribute using regular expression
 //And convert the number of milliseconds to a number type
 var birthdayMilliseconds = parseInt(obj.Birthday.replace(/\D/igm, ""));
 //Instantiate a new date format, using the number of milliseconds since January 1, 1970 as the parameter
 var birthday = new Date(birthdayMilliseconds);
 $("<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 as required
 String.prototype.toDate = function () {
 var dateMilliseconds;
 if (isNaN(this)) {
 //Use regular expressions to remove non numeric (\ d) from date attributes
 dateMilliseconds =this.replace(/\D/igm, "");
 } else {
 dateMilliseconds=this;
 }
 //Instantiate a new date format, using the number of milliseconds since January 1, 1970 as the parameter
 return new Date(parseInt(dateMilliseconds));
 };

The method todate extended above is not necessarily reasonable and powerful enough. It can be modified as needed.

Method 3:

You can select some third-party JSON tool classes, many of which have handled the date format problem. 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, take litjson as the tool class for serializing and deserializing JSON as an example. 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 of the student set
 /// </summary>
 public class GetJson : IHttpHandler
 {
 public void ProcessRequest(HttpContext context)
 {
 //Set the result of the server response 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")}
 };
 //Serialize the student collection object to get the JSON character
 string studentsJson = JsonMapper.ToJson(students);
 //Response string to client
 context.Response.Write(studentsJson);
 context.Response.End();
 }
 public bool IsReusable
 {
 get
 {
 return false;
 }
 }
 }
}

The operation results are as follows:

At this time, 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());

Method 4:

Some netizens put forward their valuable opinions on the blog. I didn’t consider the situation in MVC. In fact, handler can also be used in MVC, so the difference is not great, but there is an action in MVC specifically for the server response to JSON. The code is as follows:

using System;
using System.Web.Mvc;
namespace JSONDateMVC.Controllers
{
 public class HomeController : Controller
 {
 public JsonResult GetJson1()
 {
 //Serialize the current date and time object and allow the client to get requests
 return Json(DateTime.Now, JsonRequestBehavior.AllowGet);
 }
 }
}

Operation results:

Download a file with the content of application / JSON, the file name is getjson1, and the content is \ / date (1391418272884) \ /

From the above situation, the date format is not specially processed during serialization in MVC. We can decompile the source code:

JSON method called by return:

protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
 return this.Json(data, null, null, behavior);
}
this. Jason method
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
 return new JsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };
}

Jsonresult class is a subclass of actionresult class. Executeresult method:

From the above code, it is not difficult to see that Microsoft’s jsonresult class still uses JavaScript serializer, so the returned result is the same as that when method 1 is not processed. To solve this problem, we can derive a new class, override the executeresult method, and use JSON Net to complete the serialization, jsonresultpro The code of the CS file is as follows:

namespace JSONDateMVC.Common
{
 using System;
 using System.Web;
 using System.Web.Mvc;
 using Newtonsoft.Json;
 using Newtonsoft.Json.Converters;
 public class JsonResultPro : JsonResult
 {
 public JsonResultPro(){}
 public JsonResultPro(object data, JsonRequestBehavior behavior)
 {
 base.Data = data;
 base.JsonRequestBehavior = behavior;
 this.DateTimeFormat = "yyyy-MM-dd hh:mm:ss";
 }
 public JsonResultPro(object data, String dateTimeFormat)
 {
 base.Data = data;
 base.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
 this.DateTimeFormat = dateTimeFormat;
 }
 /// <summary>
 ///Date format
 /// </summary>
 public string DateTimeFormat{ get; set; }
 public override void ExecuteResult(ControllerContext context)
 {
 if (context == null)
 {
 throw new ArgumentNullException("context");
 }
 if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
 { 
 throw new InvalidOperationException("MvcResources.JsonRequest_GetNotAllowed");
 }
 HttpResponseBase base2 = context.HttpContext.Response;
 if (!string.IsNullOrEmpty(this.ContentType))
 {
 base2.ContentType = this.ContentType;
 }
 else
 {
 base2.ContentType = "application/json";
 }
 if (this.ContentEncoding != null)
 {
 base2.ContentEncoding = this.ContentEncoding;
 }
 if (this.Data != null)
 {
 //Convert system Datetime date format to ISO 8601 date format
 //ISO 8601 (e.g. 2008-04-12t12:53z)
 IsoDateTimeConverter isoDateTimeConverter=new IsoDateTimeConverter();
 //Format date
 isoDateTimeConverter.DateTimeFormat = DateTimeFormat;
 //Serialization
 String jsonResult = JsonConvert.SerializeObject(this.Data,isoDateTimeConverter);
 //Corresponding results
 base2.Write(jsonResult);
 }
 }
 }
}

The code using the above jsonresultpro action type is as follows:

public JsonResultPro GetJson2()
 {
 //Serialize the current date and time object and allow the client to get requests. Note that h is uppercase
 return new JsonResultPro(DateTime.Now,"yyyy-MM-dd HH:mm");
 }

Operation results:

“2014-02-03 18:10”

In this way, you can set the date format completely according to your own meaning, but you should note that the date format, such as the usual format, is different. For example, H here represents the time, if uppercase represents the 24-hour system, and if lowercase represents the 12-hour system. There are a few more questions to ask:

1. There are many changes in the code decompiled by reflector, such as the property will become get_ In the form of request () method, I don’t know if you have a better method.

2. The resource file mvcresources is used in the decompiled code JsonRequest_ How can getnotallowed be used when rewriting?

The above is a summary of the four solutions to the problem of Jason date format introduced by Xiaobian (super detailed). I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to the developeppaer website!