這個問題似乎是,你有剩餘時間String
,你想解析它的工作完成百分比。
顯然,您需要的第一件事是預計總時間。讓我們假設這也是String
。
首先編寫一個方法來解析您的HH:mm:ss
String
爲long
表示剩餘秒數。
public long parseToSeconds(final String duration) throws ParseException {
final MessageFormat durationFormat = new MessageFormat("{0,number,#}:{1,number,#}:{2,number,#}");
final Object[] parsedTimeRemaining = durationFormat.parse(duration);
final long totalDuration = TimeUnit.HOURS.toSeconds((Long) parsedTimeRemaining[0])
+ TimeUnit.MINUTES.toSeconds((Long) parsedTimeRemaining[1])
+ (Long) parsedTimeRemaining[2];
return totalDuration;
}
我們在這裏做的是使用MessageFormat
您String
解析成的Object
數組。正如我們告訴MessageFormat
這些是數字,它會自動轉換(或嘗試轉換,因此例外)到Long
。
一旦我們有這些數字,我們使用(非常有用)TimeUnit
類將它們全部縮放到秒。
一對夫婦的快速測試,以確保我們在正確的軌道上:
System.out.println(parseToSeconds("00:00:01"));
System.out.println(parseToSeconds("00:01:00"));
System.out.println(parseToSeconds("01:00:00"));
System.out.println(parseToSeconds("01:01:01"));
輸出:
看起來不錯。
爲了簡單起見,我們假設正確的過程開始時間爲了簡單起見「04:04:04」,這給出了14644
。現在我們只需要存儲它並根據任何新的持續時間String
計算百分比。這應該做的伎倆:
public int asPercentage(final long totalTime, final long remaining) {
final double percentage = remaining/((double) totalTime);
return (int) (percentage * 100);
}
注意的事實,我投(貌似毫無意義)的資料轉移到double
之一。這是因爲在Java中,對整型的任何操作總是返回另一個整型。鑄造到double
強制它返回double
。
讓我們再次做一個快速檢查:
final long totalDuration = 14644;
System.out.println(asPercentage(totalDuration, parseToSeconds("03:03:03")));
System.out.println(asPercentage(totalDuration, parseToSeconds("02:02:02")));
System.out.println(asPercentage(totalDuration, parseToSeconds("01:01:01")));
輸出:
看起來不錯,就是剩餘時間的百分比總數。也許到了我們想要的進度條。讓倒轉:
public static int asPercentage(final long totalTime, final long remaining) {
final double percentage = remaining/((double) totalTime);
return 100 - (int) (percentage * 100);
}
輸出:
阿公頃。好多了。
請定義「它根本不起作用」。告訴我們細節,任何有助於我們理解你的問題的東西。 –
您正在將一個持續時間(字符串)解析爲日期。這顯然是錯誤的。 –
'SimpleDataFormatter'是否有任何類保留這個名字。 – Masudul