为了便于传输,通信过程中传输的都是:当前时间跟标准时间相隔的秒数,并且是以16进制字节的形式传输的。
1 public double ConvertDateTimeInt(System.DateTime time)//将时间格式的数据类型转换成浮点数类型 2 { 3 double intResult = 0; 4 System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 5 intResult =(time - startTime).TotalSeconds; 6 return intResult; 7 } 8 9 public DateTime ConvertIntDatetime(double utc)10 {11 System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));12 startTime = startTime.AddSeconds(utc);13 startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 )14 return startTime;15 }
1 public byte[] ConvertDoubleByte(double d) 2 { 3 byte[] result = new byte[4]; 4 float f=(float)d; 5 result = BitConverter.GetBytes(f); 6 return result; 7 } 8 9 public double ConvertByteDouble(byte [] d)10 {11 double result=0;12 float q = BitConverter.ToSingle(d, 0);13 result = (double)q;14 return result;15 }
1 private void button1_Click(object sender, EventArgs e)//这种只是显示的形式不同,未达到目的 2 { 3 DateTime utc_tem = DateTime.UtcNow; 4 5 double utc = ConvertDateTimeInt(utc_tem);//相对应的秒数! 6 byte[] s = new byte[4]; 7 s = ConvertDoubleByte(utc); 8 9 10 DateTime mytime = ConvertIntDatetime(1429647491.3936753);11 byte[] b = new byte[4] { 0x80,0x6d,0xaa,0x4e};12 mytime = ConvertIntDatetime(ConvertByteDouble(b));13 }