2019独角兽企业重金招聘Python工程师标准>>>
java RPC服务中的localTime转换为long之后,C#没有直接转换的方法,这时候只能自己动手了.
做了几个数据实验了一下localTime转换出的long,其实就是3600*10^9小时+60*10^9分钟+ 10^9*秒+10^6*毫秒这样的格式.那么换算起来就很简单了.
当然要注意精度问题.LocalTime精度到纳秒(10^-9),而DateTime只支持到毫秒.
废话不说看代码
//从C#的DateTime转化为LocalTime的long
public static long ToJavaLocalTimeLong(DateTime time)
{
return time.Millisecond * 1000000L + time.Second * 1000000000L + time.Minute * 60000000000L + time.Hour * 3600000000000L;
}
//从LocalTime的Long转化为C#的DateTime
public static DateTime FromJavaLocalTimeLong(long time)
{
if (time < 1000000)
return new DateTime(2000, 1, 1, 0, 0, 0);
if (time > 86399999000000)
throw new Exception("时间值过大,超过23点59分59秒999,无法转换");
long lastTime = time;
int hour = Convert.ToInt32(lastTime / 3600000000000);
lastTime -= (long)hour * 3600000000000L;
int minute = Convert.ToInt32(lastTime / 60000000000);
lastTime -= (long)minute * 60000000000L;
int second = Convert.ToInt32(lastTime / 1000000000);
lastTime -= (long)second * 1000000000L;
int msecound = Convert.ToInt32(lastTime / 1000000);
return new DateTime(2000, 1, 1, hour, minute, second, msecound);
}