栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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"));
///  2. /// 将BYTE数组转换为DATETIME类型 3. ///  4. ///  5. ///  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();
  }
 }

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/121503.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号