2015-11-07 94 views
0

這是一個簡單的問題,但我沒有得到它的工作。已用時間格式HH:mm:ss

我每秒遞增一個變量並將其設置在一個格里高利的日曆中,以毫秒爲單位。

而我正在使用這種格式HH:mmss來呈現elpased時間。

問題是,小時開始顯示01而不是00.例如,1分35秒後顯示的是:01:01:35而不是00:01:35

問題出在哪裏?

有重要的代碼:

GregorianCalendar timeIntervalDone = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); //initially I didn't have the TimeZone set, but no difference 
SimpleDateFormat dateTimeIntervalFormat = new SimpleDateFormat("HH:mm:ss"); 

public String getTimeIntervalDoneAsString() { 
    timeIntervalDone.setTimeInMillis(mTimeIntervalDone); //mTimeIntervalDone is the counter: 3seccond -> mTimeIntervalDone = 3000 
    return dateTimeIntervalFormat.format(timeIntervalDone.getTime()); 
} 

回答

0

我終於明白了:

GregorianCalendar timeIntervalDone = new GregorianCalendar(); 
SimpleDateFormat dateTimeIntervalFormat = new SimpleDateFormat("HH:mm:ss"); 
dateTimeIntervalFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 
+0

缺點:只適用於小於一天(24小時)的時間間隔。 –

0

我想原因是你的時區設置爲GMT-1,但輸出是UTC。請嘗試沒有時區,它應該工作。

+0

沒有時區的結果是一樣的。 – amp

+0

哦,對不起,我沒有滾動到最後看到該評論。 –

0

你的做法是一個黑客,試圖使用日期,時間瞬間類(GregorianCalendar)來表示時間跨度。再加上你的格式不明確,看起來像一個時間而不是持續時間。

ISO 8601

另一種方法是使用說明的持續時間的ISO 8601標準方式:PnYnMnDTnHnMnS其中P標誌着開始和T年 - 月 - 日從時,分,第二部分部分分離。

java.time

在Java中8 java.time框架,後來取代了老java.util.Date/.Calendar類。舊的課程已被證明是麻煩的,混亂的和有缺陷的。避免它們。

的java.time框架由非常成功Joda-Time庫的啓發,通過JSR 310定義,由ThreeTen-Extra項目擴展,並在​​說明。

java.time框架確實使用ISO 8601作爲其默認設置,這些優秀的一組類缺少一個類來表示整個年 - 月 - 日 - 時 - 分 - 秒。相反,它將概念分解爲兩個。 Period類處理年數 - 月 - 天,而Duration類處理小時 - 分鐘 - 秒。

Instant now = Instant.now(); 
Instant later = now.plusSeconds (60 + 35); // One minute and 35 seconds later. 

Duration duration = Duration.between (now , later); 
String output = duration.toString(); 

轉儲到控制檯。

System.out.println ("output: " + output); 

輸出:PT1M35S

相關問題