C#轉換Datetime為 UnixTimeStamp方法和坑點
獲取當前時間UnixTimeStamp
DateTime.UtcNow返回以UTC表示的當前時間,Kind屬性是DateTimeKind.Utc
private static readonly long Jan1St1970Ms = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).Ticks;public static long CurrentSecondUnixTimestamp(){ return (DateTime.UtcNow.Ticks - Jan1St1970Ms) / 10000000L; }
轉換時間到UnixTimestamp
DateTime.ToUniversalTime. 將當前 DateTime 物件的值轉換為協調世界時 (UTC)。
public static long UnixTimeStampUTC(DateTime dateTime){ Int32 unixTimeStamp; DateTime zuluTime = dateTime.ToUniversalTime(); DateTime unixEpoch = new DateTime(1970, 1, 1); unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds; return unixTimeStamp; }
需要注意一下的坑點
DateTime.ToUniversalTime. 將當前 DateTime 物件的值轉換為協調世界時 (UTC)。
public static void Main() { DateTime x1 = new DateTime(2019, 1, 22,16,30,22); long x = (x1.ToUniversalTime().Ticks - 621355968000000000L) / 10000000L; long x2 = (x1.Ticks - 621355968000000000L) / 10000000L; Console.WriteLine("轉換ToUniversalTime:" + x); Console.WriteLine("未轉換ToUniversalTime:" + x2); }
如果在獲取UnixTimeStamp的時候不先ToUniversalTime
,結果可能跟你預想的就不一樣了。這個地方需要特別注意一下。
執行結果
作者:菜鳥飛不動
連結:
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2334/viewspace-2820759/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- (C#)時間戳、DateTime相互轉換C#時間戳
- pd.to_datetime方法將字串轉為datetime型字串
- Net任意String格式轉換為DateTime型別型別
- 用datetime和pytz來轉換時區
- C#字串轉換為數字的4種方法C#字串
- mysql bigint型別和datetime型別的轉換MySql型別
- 使用C#,VB和Java將PDF轉換為DOC / DOCXJava
- 帶毫秒的字元轉換成時間(DateTime)格式的通用方法字元
- C#生轉換網頁為pdfC#網頁
- 用C#把檔案轉換為XML(轉)C#XML
- c# の datetimeC#
- C#全形和半形轉換C#
- C#中,時間格式轉化,ticks,datetimeC#
- Activity轉換為View和把圖片轉換為ViewView
- 浮點數轉換為String字串(可設定精度)方法字串
- C# 列舉遍歷和轉換C#
- C# 自定義 implicit和explicit轉換C#
- 將WordPress站點轉換為JoomlaOOM
- c#中DateTime類C#
- Drawable轉換為Bitmap兩種方法
- C# bytes[]和sting互相轉換C#
- C# 將一個物件轉換為指定型別C#物件型別
- 工程座標轉換方法C#程式碼實現C#
- 將dBm轉換為W的口算方法
- Gson轉換 — json資料轉換為Object實體公共方法JSONObject
- 重學c#系列——datetime 和 datetimeoffset[二十一]C#
- c#入門-型別轉換和運算C#型別
- 程式碼換膚術(一)——C#和VB (轉)C#
- sql server-Convert DateTime 格式的轉換資料SQLServer
- Android時間戳轉換為標準Datetime(yyyy-MM-dd hh:mm:ss)格式Android時間戳
- 你真的清楚DateTime in C#嗎?C#
- C#日期格式轉換C#
- c#列舉轉換C#
- C# byte陣列與Image相互轉換的方法C#陣列
- 初探JavaScript PDF blob轉換為Word docx方法JavaScript
- C#和JAVA的RSA金鑰、公鑰轉換C#Java
- string和byte[]之間的轉換 (C#)C#
- 線上直播系統原始碼,Dart-Flutter DateTime日期轉換原始碼DartFlutter