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

问题描述:

我想创建一个构造函数,它需要几秒钟时间并将其转换为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 (timeInSeconds < 0) { 
    return MyTime(24 * 60 * 60 + timeInSeconds); 
} 

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

,可随时更换ifwhile循环,以避免递归

+0

对Sergio答案的类似评论 - 虽然在这里效率不高。 Modulo(%)好得多 –

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

是添加到构造函数的开始。 虽然如果你期望有大的负数,那么IF就会被放弃。

+0

关于“while”的部分效率不高。 Modulo好得多:-1%86400 = 86399 –

+0

刚刚尝试过......没有用。知道这是负面的,你必须这样做:86400 + num%86400;从-1获得86399。 –

+0

你是对的 - 对不起。我对Python如何在Python中工作感到困惑(它会在python中返回86​​399)。但总体思路是正确的 - %比%更有效。 –

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

}