我想创建一个构造函数,它需要几秒钟并将其转换为HH:MM:SS。我可以很容易地用积极的秒数做到这一点,但是我在负秒时遇到了一些困难。
这是我到目前为止所做的:
private final int HOUR, MINUTE, SECOND, TOTAL_TIME_IN_SECONDS;
public MyTime(int timeInSeconds) {
if (timeInSeconds < 0) {
//Convert negative seconds to HH:MM:SS
} else {
this.HOUR = (timeInSeconds / 3600) % 24;
this.MINUTE = (timeInSeconds % 3600) / 60;
this.SECOND = timeInSeconds % 60;
this.TOTAL_TIME_IN_SECONDS
= (this.HOUR * 3600)
+ (this.MINUTE * 60)
+ (this.SECOND);
}
}
如果timeInSeconds为-1,我希望时间返回23:59:59等等。
谢谢!
答案 0 :(得分:2)
if (time < 0)
time += 24 * 60 * 60;
将其添加到构造函数的开头。 如果您期望有大的负数,那么在IF中输入。
答案 1 :(得分:2)
class MyTime {
private final int HOUR, MINUTE, SECOND, TOTAL_TIME_IN_SECONDS;
private static final int SECONDS_IN_A_DAY = 86400;
public MyTime(int timeInSeconds) {
prepare(normalizeSeconds(timeInSeconds));
}
private int normalizeSeconds(int timeInSeconds) {
//add timeInSeconds % SECONDS_IN_A_DAY modulo operation if you expect values exceeding SECONDS_IN_A_DAY:
//or throw an IllegalArgumentException
if (timeInSeconds < 0) {
return SECONDS_IN_A_DAY + timeInSeconds;
} else {
return timeInSeconds;
}
}
private prepare(int timeInSeconds) {
this.HOUR = (timeInSeconds / 3600) % 24;
this.MINUTE = (timeInSeconds % 3600) / 60;
this.SECOND = timeInSeconds % 60;
this.TOTAL_TIME_IN_SECONDS
= (this.HOUR * 3600)
+ (this.MINUTE * 60)
+ (this.SECOND);
}
}
答案 2 :(得分:1)
怎么样
if (timeInSeconds < 0) {
return MyTime(24 * 60 * 60 + timeInSeconds);
}
因此它会循环,你会利用现有的逻辑。
您可以使用if
循环替换while
以避免递归