Four methods to solve the json Date Format problem: json Date Format

Source: Internet
Author: User
Tags iso 8601 iso 8601 date iso 8601 date format

Four methods to solve the json Date Format problem: json Date Format

During development, sometimes data in json format needs to be returned from the server. If the DateTime type data in the background code is serialized using the tool class provided by the system, a long number will be obtained to represent the date data, as follows:

//Set the result of the server response to plain text
context.Response.ContentType = "text/plain";
//Student object set
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 student collection object to get JSON character
string studentsJson=jss.Serialize(students);
//Respond string to client
context.Response.Write(studentsJson);
context.Response.End();

The running result is:


Among them, Tom's birthday "January 1, 1970" has changed to 1391141532000, which is actually the number of milliseconds since 1391141532000/1000; 60/60/24/365/44.11 = 1970 years, 44 + =, in this way, we can obtain the year, month, day, hour, minute, second, and millisecond. This format is a feasible representation, but not a friendly one that ordinary people can understand. How can this format be changed?

Solution:

Method 1:On the server side, convert the date format using the Select method or the 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>
///Students, 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
context.Response.ContentType = "text/plain";
//Student object set
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 you need to rename the property after it changes, 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 student collection object to get JSON character
string studentsJson = jss.Serialize(studentSet);
//Respond string to client
context.Response.Write(studentsJson);
context.Response.End();
}
public bool IsReusable
{
Get
{
return false;
}
}
}
}

The Select method re-projects the object set to convert the Birthday attribute into a new attribute. Note that the attribute must be renamed after the attribute changes. The attribute names can be the same; here, you can use the select method or the LINQ query expression, or you can select another method to achieve the same purpose. This method can remove the attributes not used by the client in the collection, to achieve simple performance optimization.

Running result:


At this time, the date format has changed to a friendly format, but in javascript this is only a string.

Method 2:

In javascript, convert the string in "Birthday": "\/Date (1391141532000) \/" to a Date object in javascript, you can delete the non-numeric characters in the Value corresponding to the Key Birthday in the form of replacement, To a number 1391141532000, and then instantiate a Date object, 1391141532000 milliseconds as the parameter, get 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");
//Use regular expression to delete non number (\ d) in birthday attribute
//And convert the number of milliseconds to the 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 id="ulStudents">
</ul>
</body>
</html>
Operation result:
Regular /D/igm is used to replace all non numbers. D represents non numbers, and IgM is a parameter, which means ignore case, multiple and global replacement, multi-line replacement, and sometimes +86 will be used. In addition, if this problem of date format needs to be handled repeatedly occurs in the project, a JavaScript method can be extended as follows:
$(function () {
$.getJSON("getJson.ashx", function (students) {
$.each(students, function (index, obj) {
$("<li/>").html(obj.Name).appendTo("#ulStudents");
//Use regular expression to delete non number (\ d) in birthday attribute
//And convert the number of milliseconds to the 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 a string object, which can be improved according to requirements
String.prototype.toDate = function () {
var dateMilliseconds;
if (isNaN(this)) {
//Use regular expression to delete non number (\ d) in date attribute
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 above extended method todate is not necessarily reasonable or powerful enough, and can be modified as needed.
Method three:
You can select some third-party JSON tool classes, some of which have already dealt with date format problems. Common JSON serialization and deserialization 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 we take litjson as an example of the tool class for serializing and deserializing JSON. The code is as follows:
using System;
using System.Collections.Generic;
using System.Web;
using LitJson;
namespace JsonDate2
{
using System.Linq;
/// <summary>
///Students, 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
context.Response.ContentType = "text/plain";
//Student object set
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 student collection object to get JSON character
string studentsJson = JsonMapper.ToJson(students);
//Respond 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 four:
Some netizens put forward their valuable opinions on this text sent to 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 specifically for the server response to JSON in MVC, and the code is as follows:
using System;
using System.Web.Mvc;
namespace JSONDateMVC.Controllers
{
public class HomeController : Controller
{
public JsonResult GetJson1()
{
//Serializes the current date and time object and allows client get requests
return Json(DateTime.Now, JsonRequestBehavior.AllowGet);
}
}
}
Operation result:
Download a file named getjson1 with the content of application / JSON, and the content is "\ / date (1391418272884) \ /"
According to the above situation, the date format is not specially processed in MVC serialization. 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.json 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 };
}
Subclass of actionresult class of jsonresult class, executeresult method:
From the above code, it is not difficult to see that the jsonresult class of Microsoft still uses JavaScript serializer, so the returned result is the same as that when the method is not processed. To solve this problem, we can derive a new class, rewrite the executeresult method, and use json.net to complete the serialization work. The code of jsonresultpro.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) &amp;&amp; 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 the date format of system.datetime 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 jsonresultpro action type above is as follows:
public JsonResultPro GetJson2()
{
/ /Serialize the current date and time object and allow client get requests, note that h is uppercase
return new JsonResultPro(DateTime.Now,"yyyy-MM-dd HH:mm");
}
Operation result:
"2014-02-03 18:10"
In this way, you can set the date format completely according to your own meaning. However, you need to pay attention to the difference between the date format and the normal format. For example, here, H stands for time. If upper case stands for 24-hour system, and if lower case stands for 12-hour system. There are also a few questions to ask:
1. There are many changes in the code obtained through decompilation of reflector. For example, the property will become the form of get ﹐ request() method. I don't know if you have a better method.
2. The resource file mvcresources.jsonrequest'getnotallowed is used in the decompiled code. How can it be used when rewriting?
Here are several ways to solve the date format problem after serialization in JSON. There should be a better and more perfect way. Welcome to tell me. Because many students asked me, I wrote this text, welcome to criticize and correct.
Sample code download
MVC sample code download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.