温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

利用C# 怎么获取当前的总毫秒数

发布时间:2021-01-14 14:15:07 来源:亿速云 阅读:1261 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关利用C# 怎么获取当前的总毫秒数,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

在.Net下DateTime.Ticks获得的是个long型的时间整数,具体表示是至0001 年 1 月 1 日午夜 12:00:00 以来所经过时间以100纳秒的数字。转换为秒为Ticks/10000000,转换为毫秒Ticks/10000。

如果要获取从1970年1月1日至当前时间所经过的毫秒数,代码如下:

//获取当前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[] 转换成 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,下面是转换方法:

 // 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);   }

调用举例:

byte[] write = DateToByte(DateTime.Now.Date);  MessageBox.Show(ByteToDate(write).ToString("yyyy-MM-dd"));
/// <summary> 2. /// 将BYTE数组转换为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();   }  }

关于利用C# 怎么获取当前的总毫秒数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI