1 回答

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個贊
一分鐘有 60 秒,一小時有 60 分鐘,一天有 24 小時,所以:
private static final int SECONDS_IN_MINUTE = 60;
private static final int SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
private static final int SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;
然后你只需要繼續(xù)劃分:
class RemainingTime {
private static final int SECONDS_IN_MINUTE = 60;
private static final int SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
private static final int SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;
private int totalSeconds, days, hours, minutes, seconds;
public RemainingTime(int totalSeconds) {
this.totalSeconds = totalSeconds;
init();
}
private void init() {
int remainingSeconds = totalSeconds;
days = remainingSeconds / SECONDS_IN_DAY;
remainingSeconds -= days * SECONDS_IN_DAY;
hours = remainingSeconds / SECONDS_IN_HOUR;
remainingSeconds -= hours * SECONDS_IN_HOUR;
minutes = remainingSeconds / SECONDS_IN_MINUTE;
remainingSeconds -= minutes * SECONDS_IN_MINUTE;
seconds = remainingSeconds;
}
public int getDays() { return days; }
public int getHours() { return hours; }
public int getMinutes() { return minutes; }
public int getSeconds() { return seconds; }
}
你像這樣使用它:
RemainingTime rt = new RemainingTime(274119);
System.out.println(String.format(
"Remaining %s day(s), %s hour(s), %s minute(s) and %s second(s)",
rt.getDays(), rt.getHours(), rt.getMinutes(), rt.getSeconds()));
輸出:
Remaining 3 day(s), 4 hour(s), 8 minute(s) and 39 second(s)
添加回答
舉報