基於.net的應用中,不會用到unix時間戳,當.net應用與其它應用(eg: php, java)交互時,就會用到unix時間戳。在項目中曾經用到過一次,用戶經過web app提交數據並分享給安卓app時,若是時間間隔在一分鐘內,數據才能算是真實有效,不然不予處理。還有asp.net開發中,常常會須要將對象序列化成json數據,js拼接成html,日期對象就會被序列化成以下形式:{「date」:」\/Date(1349839763373)\/」},js還沒法識別,這時就不妨考慮下將日期轉換成unix時間戳。php
如下是C#下的日期與unix時間戳的相互轉換:html
/// <summary> /// 日期轉換成unix時間戳 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public static long DateTimeToUnixTimestamp(DateTime dateTime) { var start = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind); return Convert.ToInt64((dateTime - start).TotalSeconds); } /// <summary> /// unix時間戳轉換成日期 /// </summary> /// <param name="unixTimeStamp">時間戳(秒)</param> /// <returns></returns> public static DateTime UnixTimestampToDateTime(this DateTime target, long timestamp) { var start = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind); return start.AddSeconds(timestamp); }
說下這個日期(1970-1-1),如今計算機和一些電子設備時間的計算和顯示是以距曆元(即格林威治標準時間 1970 年 1 月 1 日的 00:00:00.000,格里高利曆)的偏移量爲標準的,有人就戲稱英國的格林威治天文臺是「時間開始的地方」。java
附:web
1. 各語言的時間戳轉換:http://www.epochconverter.com/json
2. unix時間介紹:http://en.wikipedia.org/wiki/Unix_timeapp