簡體   English   中英

經過時間格式HH:mm:ss

[英]Elapsed time format HH:mm:ss

這是一個簡單的問題,但我無法使其正常工作。

我每秒增加一個變量,並以毫秒為單位將其設置在GregorianCalendar中。

我正在使用這種格式HH:mmss來表示提前時間。

問題是小時開始顯示01而不是00。例如,在1分35秒之后,顯示的是: 01:01:35 : 01:01: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());
}

我認為原因是您將時區設置為GMT-1,但輸出是utc。 請在沒有該時區的情況下嘗試它,它應該可以工作。

我終於明白了:

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

您的方法是破解,試圖使用日期時間矩類( GregorianCalendar )來表示時間跨度。 另外,您的格式是模棱兩可的,看起來像是一天中的時間而不是持續時間。

ISO 8601

一種替代方法是使用ISO 8601標准描述持續時間: PnYnMnDTnHnMnS ,其中P標記開始,而T則將年月日部分與時分秒部分分開。

java.time

Java 8和更高版本中的java.time框架取代了舊的java.util.Date/.Calendar類。 老類被證明是麻煩,混亂和有缺陷的。 避免他們。

java.time框架的靈感來自於JSR 310定義的,由ThreeTen-Extra項目擴展的,非常成功的Joda-Time庫,並在Tutorial中進行了說明。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM