search
HomeWeb Front-endJS TutorialJson operation date format

Json operation date format

Apr 25, 2018 pm 05:25 PM
javascriptjsonFormat

This time I will bring you the Json operation date format. What are the precautions for Json operation date format? . The following is a practical case, let’s take a look.

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, it will be serialized using the system's own tool class and a long number will be obtained to represent the date data. , as shown below:

 //设置服务器响应的结果为纯文本格式
 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();</student></student>

The running result is:

The corresponding birthday of Tom "2014-01-31" becomes 1391141532000 , this 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 years. According to this method, the year, month, day, hour, minute, second and millisecond can be obtained . This format is a feasible representation but not a friendly format that ordinary people can understand. How to change this format?

Solution:

Method 1: Use the Select method## for the date format on the server side #Or LINQ expression is converted and sent to the client:

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;
 }
 }
 }
}</student></student>
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 changes. The attribute name can be the same ; Here you can use the select method or LINQ query expression, or you can choose other methods to achieve 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 :

nbsp;html>


 <title>json日期格式处理</title>
 <script></script>
 <script>
 $(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>


 <h2 id="json日期格式处理">json日期格式处理</h2>
 
     
Running results:

uses the regular /\D/igm to replace all non-digits, \D represents non-digits, igm are parameters, respectively indicating ignoring case; multiple, global replacement; multi-line replacement; sometimes 86 will occur, 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, the code is as follows:

$(function () {
 $.getJSON("getJson.ashx", function (students) {
 $.each(students, function (index, obj) {
 $("
  • ").html(obj.Name).appendTo("#ulStudents");  //使用正则表达式将生日属性中的非数字(\D)删除  //并把得到的毫秒数转换成数字类型  var birthdayMilliseconds = parseInt(obj.Birthday.replace(/\D/igm, ""));  //实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数  var birthday = new Date(birthdayMilliseconds);  $("
  • ").html(birthday.toLocaleString()).appendTo("#ulStudents");  $("
  • ").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 above extended method toDate may not be reasonable or powerful enough, and can be modified as needed.

    Method 3:

    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 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 use litjson as 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>
     /// 学生类,测试用
     /// </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;
     }
     }
     }
    }</student></student>
    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:

    $(function () {
     $.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());

    Method 4:

    This text was posted on the blog and netizens put forward their valuable opinions. I did not consider the situation in MVC. In fact, handlers can also be used in MVC, so the difference is not It’s very big, but there is an Action in MVC specifically for 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()
     {
     //序列化当前日期与时间对象,并允许客户端Get请求
     return Json(DateTime.Now, JsonRequestBehavior.AllowGet);
     }
     }
    }
    Running results:

    下载一个内容为Application/json的文件,文件名为GetJson1,内容是"\/Date(1391418272884)\/"

    从上面的情况看来MVC中序列化时并未对日期格式特别处理,我们可以反编译看源码:

    Return调用的Json方法:

    protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
    {
     return this.Json(data, null, null, behavior);
    }
    this.Json方法
    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类ActionResult类的子类,ExecuteResult方法:

    从上面的代码中不难看出微软的JsonResult类仍然是使用了JavaScriptSerializer,所以返回的结果与方法一未处理时是一样的,要解决这个问题我们可以派生出一个新的类,重写ExecuteResult方法,使用Json.net来完成序列化工作,JsonResultPro.cs文件的代码如下:

    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>
     /// 日期格式
     /// </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)
     {
     //转换System.DateTime的日期格式到 ISO 8601日期格式
     //ISO 8601 (如2008-04-12T12:53Z)
     IsoDateTimeConverter isoDateTimeConverter=new IsoDateTimeConverter();
     //设置日期格式
     isoDateTimeConverter.DateTimeFormat = DateTimeFormat;
     //序列化
     String jsonResult = JsonConvert.SerializeObject(this.Data,isoDateTimeConverter);
     //相应结果
     base2.Write(jsonResult);
     }
     }
     }
    }

    使用上面的JsonResultPro Action类型的代码如下:

     public JsonResultPro GetJson2()
     {
     //序列化当前日期与时间对象,并允许客户端Get请求,注意H是大写
     return new JsonResultPro(DateTime.Now,"yyyy-MM-dd HH:mm");
     }

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    jsonp+json实现AJAX跨域请求

    Jsonp怎样才能解决ajax跨域

    The above is the detailed content of Json operation date format. For more information, please follow other related articles on the PHP Chinese website!

  • 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
    From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

    JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

    Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

    Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

    The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

    C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

    JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

    JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

    JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

    The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

    Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

    Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

    Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    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 Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software