Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert negative seconds to hour:minute:second

Tags:

java

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!

like image 571
OverflowingJava Avatar asked Sep 25 '16 22:09

OverflowingJava


People also ask

What is the formula to convert seconds to hours?

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.

How do you convert 1 second to an hour?

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.


1 Answers

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.

like image 123
Sergio Tx Avatar answered Sep 30 '22 09:09

Sergio Tx