将负秒转换为小时:分钟:秒

5
我希望创建一个构造函数,将输入的秒数转换为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等。谢谢!
3个回答

2
if (time < 0)
    time += 24 * 60 * 60;

将其添加到构造函数的开头。 如果您预计会有较大的负数,则使用While而不是IF。


关于“while”的部分效率不是很高。取模运算更好:-1%86400 = 86399 - Piotr Reszke
刚试了一下...不行。知道它是负数,你必须这样做:86400 + num%86400; 以从-1获得86399。 - Sergio Tx
你是对的 - 抱歉。我在Python中对%的工作方式感到困惑(它会返回86399)。但总体思路仍然是正确的 - %比while更有效率。 - Piotr Reszke

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);
  }

}

1

怎么样?

if (timeInSeconds < 0) {
    return MyTime(24 * 60 * 60 + timeInSeconds);
}

因此,它会循环,并且您将利用现有的逻辑。
您可以将if替换为while循环以避免递归。

类似于Sergio的回答,这里使用while不是很高效。取模(%)更好。 - Piotr Reszke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接