首页 / 软件开发 / JAVA / Java与C#实现时间转换
Java与C#实现时间转换2010-12-22这两天做了一个Web Service,要记录操作时间,定义为long型数据,因为 Java中可以把当前时间表示成long类型。Java中可以用 System.currentTimeMillis() 获取当前时间的long形式,它 的标示形式是从1970年1月1日起的到当前的毫秒的数。Web Service 是用Java写 的,把这个long型数据转成timestamp再存入MySQL,所以用调用我们的Web Service可以直接把这个值传入。但是.Net下计算时间的方式不太一样,它是计算单位是Ticks,关于Ticks,msdn上是这样说的:A single tick represents one hundred nanoseconds or one ten- millionth of a second. The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001.就是从公元元年元月1日午夜到指定时间的千万分之一秒了,为了和Java比较 ,说成万分之一毫秒。( System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks)/10000;如果要得到Java中 System.currentTimeMillis() 一样的结果,就可以写成 上面那样,也可以这样写:TimeSpan ts=new TimeSpan( System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);(long)ts.TotalMilliseconds;需要注意的是这里是用的 System.DateTime.UtcNow 而不是 System.DateTime.Now ,因为我们在东八区,如果用后面那种形式就会发现时间 会和想象当中的差了8个小时。