I would like to create a constructor that takes in seconds and converts it to HH:MM:SS. I can do this pretty easily with positive seconds, but I'm running into some difficulty with negative seconds.
Here is what I have so far:
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);
}
}
If the timeInSeconds is -1 I want the time to return 23:59:59, etc.
Thanks!
We can divide an amount of time in seconds by 3600 to determine how many hours it is equivalent. To use the seconds to hours converter: Enter the time in seconds, say 7,260 seconds. The seconds to hours converter will return the number of hours as 7,260/3600 = 2.0167 hours or 2 hours 1 minute.
There are 3,600 seconds in 1 hour. The easiest way to convert seconds to hours is to divide the number of seconds by 3,600. To understand the reason for this conversion, it can be helpful to set up conversion tables, in which you first convert the number of seconds to minutes, and then the number of minutes to hours.
if (time < 0)
time += 24 * 60 * 60;
Add that to the start of the constructor. While insted of IF if you expect big negative numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With