软件编程
位置:首页>> 软件编程>> C#编程>> C# 获取当前总毫秒数的实例讲解

C# 获取当前总毫秒数的实例讲解

作者:凡梦_  发布时间:2023-02-22 12:57:00 

标签: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();
 }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

来源:https://blog.csdn.net/mpegfour/article/details/78611693

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com