2014-07-16 50 views
0

基本上我有一個應用程序,其首先要求用戶輸入然後當用戶點擊提交它需要當前時間並將其存儲在與SharedPreferences以下代碼:機器人:毫秒時間長 - 一小時的精度損失

SubmitAction.java

ConversePrefs cp = new ConversePrefs(Awake.this); 
Date date = new Date(System.currentTimeMillis()); 
cp.SetStartTime(date.getTime()); 

ConversePrefs.java:

public void SetStartTime(long start){ 
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0); 
    SharedPreferences.Editor editor = settings.edit(); 
    editor.putLong("StartTime", start); 
    editor.commit(); 
} 
public long GetStartTime(){ 
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0); 
    long setting = settings.getLong("StartTime", 0); 
    return setting; 
    } 

所有行動和應用程序的功能後,完成,用戶被帶到新的活動它獲取的開始時間和在當前時間使用它。

FinalActivity.java:

final ConversePrefs cp = new ConversePrefs(this); 
    final long start_time = cp.GetStartTime(); 
    final SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss"); 
    Date date = new Date(System.currentTimeMillis()); 
    long end_time = date.getTime(); 
    long final_time = end_time - start_time; 
    String dateString = formatter.format(new Date(final_time)); 

dateString結束了表示一小時抵消。 示例:

我點擊了提交按鈕:02:40:22 AM 應用程序執行了所有操作並在13秒內打開了新的活動。 我最終有計數器說: 時間經過:01:00:13

因此它增加了一個小時,這個問題/原因是什麼?

我在UTC時區的方式,如果重要的話。

+1

關閉1小時幾乎總是意味着DST問題。 –

+0

@GabeSechan:不過,我想。 – Thilo

+0

嗯。是的,在這個特定的一箇中,你的答案可能是對的。 –

回答

2

不要使用DateFormatter格式化「流逝的時間」。這不是爲了這個。你實際上在這裏格式化的是1970年1月某個日期的時間部分,你可能被時區或DST問題絆倒。爲什麼不把秒數作爲整數(或雙精度)打印?如果您已經使用Commons Lang,則有DurationFormatUtils

+0

第一個解決方案不起作用 - HH格式仍然偏移了一個小時。 – arleitiss

+0

好吧,那真的是時區問題。不要在這裏使用DateFormatter。 – Thilo

+0

所以你建議: 而不是使用DateFormatter - 只要做: final_time = NewTime - OldTime; difference = final_time/1000; 這給差以秒,然後只格式中使用類似的東西: 小時=差/ 3600 分鐘=(差/ 60)%60 秒=差%60 那樣? – arleitiss