java的Date.getTime()转换成C#的Datetime.ticks

先来个名词解释:
Epoch time:指从1970年1月1日零时起到现在为止的"second(秒) 数".
注意我给"second(秒) 数"加了引号,是因为在不一样的项目中,计量单位可能是不同的,需要仔细的阅读相关文档.比如Gtalk Api的Gmail Notifications文档中,所使用的date数为从1970年1月1日零时起到现在为止的"millisecond(毫秒) 数".
C#的Datetime.ticks:指从0001年1月1日零时起到现在为止的one ten-millionth of a second数量,或者one hundred nanoseconds of a second数量,也就是"千万分之一秒"的数量.
java的Date.getTime():这个方法返回目标时间到1970年1月1日零时为止的"millisecond(毫秒) 数".

然后来做个转换:
1 second(秒)=1000 millisecond(毫秒)=10 x 100 0000 one ten-millionth of a second(千万分之一秒)

好了,接下来是我们的java转换函数

 public static long GetTicks(String epochStr)
 {
  //convert the target-epoch time to a well-format string
   String date = new java.text.SimpleDateFormat("yyyy/MM/dd/HH/mm/ss").format(new Date (Long.parseLong(epochStr)));
   String[] ds=date.split("/");
    
   //start of the ticks time
  Calendar calStart=Calendar.getInstance();
  calStart.set(1, 1, 3, 0, 0, 0);
  
  //the target time
  Calendar calEnd=Calendar.getInstance();
  calEnd.set(Integer.parseInt(ds[0]) ,Integer.parseInt(ds[1]),Integer.parseInt(ds[2]),Integer.parseInt(ds[3]),Integer.parseInt(ds[4]),Integer.parseInt(ds[5]) );
  
  //epoch time of the ticks-start time
  long epochStart=calStart.getTime().getTime();
  //epoch time of the target time
  long epochEnd=calEnd.getTime().getTime();
  
  //get the sum of epoch time, from the target time to the ticks-start time
   long all=epochEnd-epochStart;   
   //convert epoch time to ticks time
      long ticks=( (all/1000) * 1000000) * 10;
    
      return ticks;
 }

用图来说明:

    |       |         |
目标时间  1970年    0001年

我是分别取得目标时间和0001年到1970年的"millisecond(毫秒) 数",然后加在一起,这样就得到了目标时间到0001年的"millisecond(毫秒) 数",然后把这个数字换算成"千万分之一秒"的数量,得到ticks数.
或许你会发现,为什么0001年的计算从1月3号起,不是应该1月1号吗.这个问题我也很奇怪,因为我发现如果从1月1号起,时间上就总是差着两天,这原因等待高手来解决 :)

posted on 2008-07-16 15:51  Notus|南色的风  阅读(6845)  评论(3编辑  收藏  举报