搜尋
首頁web前端js教程Json操作日期格式

Json操作日期格式

Apr 25, 2018 pm 05:25 PM
javascriptjson格式

這次帶給大家Json操作日期格式,Json操作日期格式的注意事項有哪些,以下就是實戰案例,一起來看一下。

開發中有時候需要從伺服器端返回json格式的數據,在後台程式碼中如果有DateTime類型的數據使用系統自帶的工具類序列化後將得到一個很長的數字表示日期數據,如下所示:

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

運行結果是:

其中Tom所對應生日「2014-01-31」變成了1391141532000 ,這其實是1970 年1 月1 日至今的毫秒數;1391141532000/1000/60/60/24/365=44.11年,44 1970=2014年,依此方法可以得出年時分時分和毫秒。這種格式是一種可行的表示形式但不是一般人可以看懂的友善格式,怎麼讓這個格式改變?

解決方法:

#方法1:在伺服器端將日期格式使用Select方法或LINQ表達式轉換後發到客戶端:

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方法重新投影物件集合將Birthday屬性轉換成一個新的屬性,注意屬性變更後要重新命名,屬性名稱可以相同;這裡可以使用select方法也可以使用LINQ查詢表達式,也可以選擇別的方式達到相同的目的;這種辦法可以將集合中客戶端不用的屬性剔除,達到簡單優化效能的目的。

運行結果:

這時候的日期格式就已經變成友善格式了,不過在javascript中這只是一個字串。

方法二:

在javascript中將"Birthday":"\/Date(1391141532000)\/"中的字串轉換成javascript中的日期對象,可以將Birthday這個Key所對應的Value中的非數字字元以替換的方式刪除,到到一個數字1391141532000,然後實例化一個Date對象,將1391141532000毫秒作為參數,得到一個javascript中的日期對象,代碼如下:

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>
 
     

運行結果:

上的使用正規/\D/igm達到替換所有非數字的目的,\D表示非數字,igm是參數,分別表示忽略(ignore)大小寫;多次、全域(global)替換;多行替換(multi-line);有些時候還會出現86的情況,只需要變換正規同樣可以達到目的。另外如果專案中反覆出現這種需要處理日期格式的問題,可以擴充一個javascript方法,程式碼如下:

$(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));  };

       上面擴充的方法toDate不一定合理,也不夠強大,可以根據需要修改。

    方法三:

    可以選擇一些第三方的json工具類,其中不乏有一些已經對日期格式問題已處理好了的,常見的json序列化與反序列化工具庫有:

    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

    這裡以litjson為序列化與反序列化json的工具類別作範例,程式碼如下:

    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>

    運行結果如下:

    #這時候的日期格式就基本上正確了,只要在javascript中直接實例化日期就好了,

    var date = new Date("01/31/2014 12:12:12");
    alert(date.toLocaleString());

    客戶端的程式碼如下:

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

    方法四:

    這點文字發到博客上有網友提出了他們寶貴的意見,我並沒有考慮在MVC中的情況,其實MVC中也可以使用handler,所以區別不是很大了,但MVC中有專門針對伺服器回應為JSON的Action,程式碼如下:

    using System;
    using System.Web.Mvc;
    namespace JSONDateMVC.Controllers
    {
     public class HomeController : Controller
     {
     public JsonResult GetJson1()
     {
     //序列化当前日期与时间对象,并允许客户端Get请求
     return Json(DateTime.Now, JsonRequestBehavior.AllowGet);
     }
     }
    }

    運行結果:

    下载一个内容为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跨域

    以上是Json操作日期格式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

  • 陳述
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
    JavaScript框架:為現代網絡開發提供動力JavaScript框架:為現代網絡開發提供動力May 02, 2025 am 12:04 AM

    JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

    JavaScript,C和瀏覽器之間的關係JavaScript,C和瀏覽器之間的關係May 01, 2025 am 12:06 AM

    引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr

    node.js流帶打字稿node.js流帶打字稿Apr 30, 2025 am 08:22 AM

    Node.js擅長於高效I/O,這在很大程度上要歸功於流。 流媒體匯總處理數據,避免內存過載 - 大型文件,網絡任務和實時應用程序的理想。將流與打字稿的類型安全結合起來創建POWE

    Python vs. JavaScript:性能和效率注意事項Python vs. JavaScript:性能和效率注意事項Apr 30, 2025 am 12:08 AM

    Python和JavaScript在性能和效率方面的差異主要體現在:1)Python作為解釋型語言,運行速度較慢,但開發效率高,適合快速原型開發;2)JavaScript在瀏覽器中受限於單線程,但在Node.js中可利用多線程和異步I/O提升性能,兩者在實際項目中各有優勢。

    JavaScript的起源:探索其實施語言JavaScript的起源:探索其實施語言Apr 29, 2025 am 12:51 AM

    JavaScript起源於1995年,由布蘭登·艾克創造,實現語言為C語言。 1.C語言為JavaScript提供了高性能和系統級編程能力。 2.JavaScript的內存管理和性能優化依賴於C語言。 3.C語言的跨平台特性幫助JavaScript在不同操作系統上高效運行。

    幕後:什麼語言能力JavaScript?幕後:什麼語言能力JavaScript?Apr 28, 2025 am 12:01 AM

    JavaScript在瀏覽器和Node.js環境中運行,依賴JavaScript引擎解析和執行代碼。 1)解析階段生成抽象語法樹(AST);2)編譯階段將AST轉換為字節碼或機器碼;3)執行階段執行編譯後的代碼。

    Python和JavaScript的未來:趨勢和預測Python和JavaScript的未來:趨勢和預測Apr 27, 2025 am 12:21 AM

    Python和JavaScript的未來趨勢包括:1.Python將鞏固在科學計算和AI領域的地位,2.JavaScript將推動Web技術發展,3.跨平台開發將成為熱門,4.性能優化將是重點。兩者都將繼續在各自領域擴展應用場景,並在性能上有更多突破。

    Python vs. JavaScript:開發環境和工具Python vs. JavaScript:開發環境和工具Apr 26, 2025 am 12:09 AM

    Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

    See all articles

    熱AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智慧驅動的應用程序,用於創建逼真的裸體照片

    AI Clothes Remover

    AI Clothes Remover

    用於從照片中去除衣服的線上人工智慧工具。

    Undress AI Tool

    Undress AI Tool

    免費脫衣圖片

    Clothoff.io

    Clothoff.io

    AI脫衣器

    Video Face Swap

    Video Face Swap

    使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

    熱工具

    記事本++7.3.1

    記事本++7.3.1

    好用且免費的程式碼編輯器

    SublimeText3 Mac版

    SublimeText3 Mac版

    神級程式碼編輯軟體(SublimeText3)

    SecLists

    SecLists

    SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

    SublimeText3漢化版

    SublimeText3漢化版

    中文版,非常好用

    Dreamweaver Mac版

    Dreamweaver Mac版

    視覺化網頁開發工具