繁体   English   中英

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

[英]Convert negative seconds to hour:minute:second

我想创建一个几秒钟的构造函数,并将其转换为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等。

谢谢!

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

将其添加到构造函数的开头。 如果您期望大的负数,那么输入IF。

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

}

怎么样

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

因此它会循环,你会利用你现有的逻辑。

您可以使用while循环替换if以避免递归

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM