1

I am required to store a time value in an integer in the format of HHMMSS. this time value is incrementing every second (basically a custom clock). however, since integers are naturally 10 based, I must implement a large cumbersome logic that extracts each digits and checks for 60 seconds in a minutes, 60 minutes in an hour and 24 hours a day. I wonder if there is some clever ways to do it without a massive if/else if chunk.

2
  • 1
    Are you sure that it wouldn't be easier to use a Calendar or DateTime (from the popular JodaTime library) and convert the value to that strange integer format you need when you need it? Commented Oct 14, 2012 at 1:49
  • 2
    If this is a real (as distinct from teaching) problem, my first reaction would be to say that storing HHMMSS time in an integer like that is daft. Use separate fields for the hours, minutes and seconds ... or deal with it when you render the (single) integer field for display. Commented Oct 14, 2012 at 2:04

2 Answers 2

2

You can use the modulus operator to pick out each of the components of a single seconds counter:

int totalSeconds;
...
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = (totalSeconds / 3600);

Then you can just increment a single seconds counter and extract each of the components.

Sign up to request clarification or add additional context in comments.

Comments

1

My suggestion would be to implement a CustomClock class, which could look something like:

public class CustomClock {
    private int hour;
    private int minute;
    private int second;

    public CustomClock(int hour, int minute, int second) {
        this.hour = hour;
        // ...
    }

    public void increment() {
        second = second + 1)%60;
        if (second == 0) minute = (minute + 1)%60;
        if (minute == 0) hour = (hour + 1)%24;
    }
}

Thus taking advantage of the mod operator (%) to compute arbitrary base numbers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.