Fish Li今天發了一篇火爆的《ASP.NET常被忽視的一些細節》,其中有一個地方我認為他大大的冤枉了微軟.Net 類庫設計人員,你打開鏈接就直接跳到了重點,先直接粘貼過來引用如下:
以上抱怨其實是沒有對javascript時間有正確的理解 , 在mozilla開發者網絡看了一篇文章, 介紹js Date對象的 , 詳情見:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FDate
截取其中一段對Date對象的描述原文如下:
Description
If you supply no arguments, the constructor creates a JavaScript Date
object for today's date and time according to local time. If you supply some arguments but not others, the missing arguments are set to 0. If you supply any arguments, you must supply at least the year, month, and day. You can omit the hours, minutes, seconds, and milliseconds.
The JavaScript date is measured in milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The JavaScript Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.
The JavaScript Date
object provides uniform behavior across platforms.
The JavaScript Date
object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.
Invoking JavaScript Date
in a non-constructor context (i.e., without the new operator) will return a string representing the current time.
黑體部分是重點中的重點,大意是: javascript 日期以1970年1月1日的世界標准時的到現在的毫秒數計量,一天有86400000毫秒, js日期范圍是世界標准時1970年1月1日之前的100000000天到其后的100000000天。
下面我們來看看MSDN上微軟對JavaScriptSerializer 對象的說明,參見鏈接:http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
下面是對.net類型和json類型的映射表格的一個截圖, 詳細見上面鏈接:
以上說明了.NET DateTime 轉換為JSON格式是以javascript標准日期為基准, 以1970-1-1半夜與當前UTC格式日期相隔的毫秒數為轉換結果,這樣我們在js中我們可以用Date對象內置函數隨意轉換為本地格式或其他格式,這樣 Fish Li所言的“不過,這個類有一個問題,在序列化DataTime類型時,它生成的結果會讓所有人感覺別扭, 其實序列化的結果表現形式還個小問題,在前端寫個轉換函數就能解決” 就完全不是問題了, 因為根本不需要寫什么轉換函數,下面是測試代碼:
DateTime now = DateTime.Now; Console.WriteLine(now.ToString()); JavaScriptSerializer js = new JavaScriptSerializer(); string json = js.Serialize(now); Console.WriteLine(json);
執行結果截圖如下:
將JSON字符結果放到javascript中運行如下:
以上說明其序列化結果表現形式在js環境中完全不是問題, 那在持久化處理中有大問題嗎, 還是以Fish Li 的代碼來說明:
DateTime dt1 = DateTime.Now;
JavaScriptSerializer jss = new JavaScriptSerializer();
string json = jss.Serialize(dt1);
DateTime dt2 = jss.Deserialize<DateTime>(json);
context.Response.Write(dt1 == dt2);
瀏覽器顯示的結果會讓人感到很意外,竟然是:False

你要寫的是通用的代碼,不僅只處理一個DateTime類型,你不知道哪個類型中有DateTime屬性,你打算怎么辦?”
class Test { private DateTime date = DateTime.Now; /// <summary> /// Datetime format Date /// </summary> public DateTime Date { get { return date; } set { date = value; } } /// <summary> /// String format Date /// </summary> public String DateString { get { return date.ToString(); } } }
其實主流的JSON轉換函數都是如MS庫相同處理,所以我沒法想到一個比標准還標准的所謂通用解決方案了 哎, 今天又沒多少時間寫win8 博客園客戶端了 。。