C# 獲取當前總毫秒數(shù)的實例講解
在.Net下DateTime.Ticks獲得的是個long型的時間整數(shù),具體表示是至0001 年 1 月 1 日午夜 12:00:00 以來所經(jīng)過時間以100納秒的數(shù)字。轉(zhuǎn)換為秒為Ticks/10000000,轉(zhuǎn)換為毫秒Ticks/10000。
如果要獲取從1970年1月1日至當前時間所經(jīng)過的毫秒數(shù),代碼如下:
//獲取當前Ticks long currentTicks= DateTime .Now.Ticks; DateTime dtFrom = new DateTime (1970, 1, 1, 0, 0, 0, 0); long currentMillis = (currentTicks - dtFrom.Ticks) / 10000;
類似于Java中:System.currentTimeMillis()
換算單位:
1秒 = 1000毫秒
1毫秒 = 1000微妙
1微秒 = 1000納秒
補充:C# 將時間戳 byte[] 轉(zhuǎn)換成 datetime 的幾個方法
推薦方法:
DateTime now = DateTime.Now; byte[] bts = BitConverter.GetBytes(now.ToBinary()); DateTime rt = DateTime.FromBinary(BitConverter.ToInt64(bts, 0));
用了2個byte,日期范圍 2000-01-01 ~ 2127-12-31,下面是轉(zhuǎn)換方法:
// Date -> byte[2] public static byte[] DateToByte(DateTime date) { int year = date.Year - 2000; if (year < 0 || year > 127) return new byte[4]; int month = date.Month; int day = date.Day; int date10 = year * 512 + month * 32 + day; return BitConverter.GetBytes((ushort)date10); } // byte[2] -> Date public static DateTime ByteToDate(byte[] b) { int date10 = (int)BitConverter.ToUInt16(b, 0); int year = date10 / 512 + 2000; int month = date10 % 512 / 32; int day = date10 % 512 % 32; return new DateTime(year, month, day); }
調(diào)用舉例:
byte[] write = DateToByte(DateTime.Now.Date); MessageBox.Show(ByteToDate(write).ToString("yyyy-MM-dd"));
/// <summary> 2. /// 將BYTE數(shù)組轉(zhuǎn)換為DATETIME類型 3. /// </summary> 4. /// <param name="bytes"></param> 5. /// <returns></returns> 6. private DateTime BytesToDateTime(byte[] bytes) { if (bytes != null && bytes.Length >= 5) { int year = 2000 + Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[0] }, 0)); int month = Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[1] }, 0)); int date = Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[2] }, 0)); int hour = Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[3] }, 0)); int minute = Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[4] }, 0)); DateTime dt = new DateTime(year, month, date, hour, minute, 0); return dt; } else19. { return new DateTime(); } }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
直接在線預(yù)覽Word、Excel、TXT文件之ASP.NET
這篇文章主要用asp.net技術(shù)實現(xiàn)直接在線預(yù)覽word、excel、txt文件,有需要的朋友可以參考下2015-08-08WPF中不規(guī)則窗體與WindowsFormsHost控件兼容問題的解決方法
這篇文章主要介紹了WPF中不規(guī)則窗體與WindowsFormsHost控件兼容問題的解決方法,對比以往的解決方案,給出了一個具有普遍性的技巧,具有一定的借鑒價值,需要的朋友可以參考下2014-11-11詳解c#中Array,ArrayList與List<T>的區(qū)別、共性與相互轉(zhuǎn)換
本文詳細講解了c#中Array,ArrayList與List<T>的區(qū)別、共性與相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12