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