java的Date.getTime()轉換成C#的Datetime.ticks

來源:互聯網
上載者:User

先來個名詞解釋:
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號起,時間上就總是差著兩天,這原因等待高手來解決

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.