在.Net下DateTime.Ticks获得的是个long型的时间整数,具体表示是至0001年1月1日午夜12:00:00以来所经过时间以100纳秒的数字。转换为秒为Ticks/10000000,转换为毫秒Ticks/10000。
如果要获取从1970年1月1日至当前时间所经过的毫秒数,代码如下:
//获取当前Ticks longcurrentTicks=DateTime.Now.Ticks; DateTimedtFrom=newDateTime(1970,1,1,0,0,0,0); longcurrentMillis=(currentTicks-dtFrom.Ticks)/10000;
类似于Java中:System.currentTimeMillis()
换算单位:
1秒=1000毫秒
1毫秒=1000微妙
1微秒=1000纳秒
补充:C#将时间戳byte[]转换成datetime的几个方法
推荐方法: DateTimenow=DateTime.Now; byte[]bts=BitConverter.GetBytes(now.ToBinary()); DateTimert=DateTime.FromBinary(BitConverter.ToInt64(bts,0));
用了2个byte,日期范围2000-01-01~2127-12-31,下面是转换方法:
//Date->byte[2] publicstaticbyte[]DateToByte(DateTimedate) { intyear=date.Year-2000; if(year<0||year>127) returnnewbyte[4]; intmonth=date.Month; intday=date.Day; intdate10=year*512+month*32+day; returnBitConverter.GetBytes((ushort)date10); } //byte[2]->Date publicstaticDateTimeByteToDate(byte[]b) { intdate10=(int)BitConverter.ToUInt16(b,0); intyear=date10/512+2000; intmonth=date10%512/32; intday=date10%512%32; returnnewDateTime(year,month,day); }
调用举例: byte[]write=DateToByte(DateTime.Now.Date); MessageBox.Show(ByteToDate(write).ToString("yyyy-MM-dd"));
///<summary>2.///将BYTE数组转换为DATETIME类型3.///</summary>4.///<paramname="bytes"></param>5.///<returns></returns>6.privateDateTimeBytesToDateTime(byte[]bytes) { if(bytes!=null&&bytes.Length>=5) { intyear=2000+Convert.ToInt32(BitConverter.ToString(newbyte[1]{bytes[0]},0)); intmonth=Convert.ToInt32(BitConverter.ToString(newbyte[1]{bytes[1]},0)); intdate=Convert.ToInt32(BitConverter.ToString(newbyte[1]{bytes[2]},0)); inthour=Convert.ToInt32(BitConverter.ToString(newbyte[1]{bytes[3]},0)); intminute=Convert.ToInt32(BitConverter.ToString(newbyte[1]{bytes[4]},0)); DateTimedt=newDateTime(year,month,date,hour,minute,0); returndt; } else19.{ returnnewDateTime(); } }
上述就是C#学习教程:C# 获取当前总毫秒数的实例讲解分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/903599.html