2016-09-25 241 views
4

我想創建一個構造函數,它需要幾秒鐘時間並將其轉換爲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等

謝謝!

回答

1

如何

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

因此它會循環,你將利用現有的邏輯。

,可隨時更換ifwhile循環,以避免遞歸

+0

對Sergio答案的類似評論 - 雖然在這裏效率不高。 Modulo(%)好得多 –

2
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)。但總體思路是正確的 - %比%更有效。 –

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

} 
相關問題