-2

I want to convert an elapsed amount of accumulated seconds into hours:minutes:seconds. For example

93599 seconds to:

25:59:59

How can I do that? (Note: 24h should not wrap to 0h)

JohnyTex
  • 3,323
  • 5
  • 29
  • 52
  • Think about the division and remainder operators. (Or use `java.time` or Joda Time...) – Jon Skeet Jul 14 '15 at 15:54
  • 2
    @JohnyText Stack Overflow is filled with similar questions. What prompted you to post a question and answer it yourself within 2 minutes of posting the question? – Chetan Kinger Jul 14 '15 at 16:01
  • Because I couldn't find a good answer on accumulated time, then writing a solution and fabricated a question so that others (and me) could benefit from having an accumulated time formatter. :-) – JohnyTex Jul 14 '15 at 16:02
  • But I also wanted to know if someone had a super solution, that didn't involve subtracting and modulus and crap... – JohnyTex Jul 14 '15 at 16:05
  • @JohnyTex So your answer is better than countless other answers already posted for the same question? Why not post an answer to those questions? – Chetan Kinger Jul 14 '15 at 16:05
  • I couldn't find the exact question. If you can hand it to me I will remove my question and post my suggestion there. – JohnyTex Jul 14 '15 at 16:06
  • @JohnyTex Try [this](http://stackoverflow.com/questions/625433/how-to-convert-milliseconds-to-x-mins-x-seconds-in-java/625624#625624) and [this](http://stackoverflow.com/questions/9027317/how-to-convert-milliseconds-to-hhmmss-format) and [this](http://stackoverflow.com/questions/22545644/how-to-convert-seconds-into-hhmmss)... and that just took me 30 seconds to find. – Chetan Kinger Jul 14 '15 at 16:35
  • They all seem to wrap back to 0h at 24h, no? – JohnyTex Jul 14 '15 at 16:37
  • 1
    So accumulate the hours, got it. – Sotirios Delimanolis Jul 14 '15 at 16:50
  • Also check out this: http://stackoverflow.com/questions/11357945/java-convert-seconds-into-day-hour-minute-and-seconds-using-timeunit – Rahul Prasad Jul 14 '15 at 16:53

4 Answers4

3

The modulus operator % is useful here. Something like this would work well

public static void convertTime(int seconds) {
    int secs = seconds % 60;
    int mins = (seconds / 60) % 60;
    int hours = (seconds / 60) / 60;
    System.out.printf("%d:%d:%d", hours, mins, secs);
}
The Beanstalk
  • 798
  • 1
  • 5
  • 20
1

Java 8 provides the java.time.Duration class for expressing amounts of time. You can use Duration#ofSeconds(long) to build an instance from an amount of seconds.

Duration ellapsed = Duration.ofSeconds(93599);

However, the default toString format looks like

PT25H59M59S

which isn't what you want. You can do the math yourself (with the various toMinutes, toHours, etc.) to convert it to the format you want. An example is given here.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

hours = 93599 / 3600. Use integer arithmetic to force a truncation.

Then subtract hours * 3600 from 93599. Call that foo. Or compute 93599 % 3600.

minutes = foo / 60. Use integer arithmetic.

Subtract minutes * 60 from foo. Call that bar. Or compute foo % 60.

bar is the remaining seconds.

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78
-4

Copy and use this Class:

public class AccumulatedTimeFormat extends Format {

@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    Long totalSeconds;

    if(obj instanceof Byte) {
        totalSeconds=((Byte)obj).longValue();
    } else if(obj instanceof Short) {
        totalSeconds=((Short)obj).longValue();
    } else if(obj instanceof Integer) {
        totalSeconds=((Integer)obj).longValue();
    } else if(obj instanceof Long) {
        totalSeconds=((Long)obj);
    } else {
        throw new IllegalArgumentException("Cannot format given Object as an accumulated-time String!");
    }

    long ss = Math.abs(totalSeconds) % 60;
    long mm = (Math.abs(totalSeconds) / 60) % 60;
    long h = (Math.abs(totalSeconds) / 60) / 60;

    if(totalSeconds<0) {
        toAppendTo.append('-');
    }
    toAppendTo.append(String.format("%d:%02d:%02d", h, mm, ss));

    return toAppendTo;
}

@Override
public Object parseObject(String source, ParsePosition pos) {
    //TODO Implement if needed!
    return null;
}

}

Like this:

System.out.println((new AccumulatedTimeFormat()).format(93599));

Which prints:

25:59:59
JohnyTex
  • 3,323
  • 5
  • 29
  • 52
  • 1
    Well it looks like massive overkill, to start with... and with no explanation (the important three lines being buried in the middle) it's not going to be much help to future visitors. – Jon Skeet Jul 14 '15 at 15:57
  • I disagree -you simple copy the class and do (new AccumulatedTimeFormat()).format(93599); – JohnyTex Jul 14 '15 at 15:58
  • That doesn't mean it's not overkill... (The fact that it only supports *part* of what `Format` is meant to be is a good indication that it's not really a good solution... if you only need the formatting part, and only need it for `int` or `long` (as is likely) then you can do it in about 5 lines.) – Jon Skeet Jul 14 '15 at 16:05
  • 2
    `int h=(int)(Math.abs(totalSeconds)/3600);` could overflow for some values of `totalSeconds`. Also, a double might not convert to a long. I wouldn't trust this code further than I could spit an elephant. – P45 Imminent Jul 14 '15 at 16:05
  • @P45Imminent Splitting an elephant is pretty simple in Java. `"elephant".split("")`.. But I agree with you. This code is no better than splitting an elephant in Java. – Chetan Kinger Jul 14 '15 at 16:08
  • Thanks for input. I changed to long. – JohnyTex Jul 14 '15 at 16:12
  • It could of course be overkill but the next time I have this problem I could solve it without thinking at all. Just copy the class and use the format. That is why I like it. With other stuff I have to declare variables and a lot of hazzle. Help me get it 100% instead. – JohnyTex Jul 14 '15 at 16:15
  • 1
    And your poor eventual successor of your code base will ask "why, why, did they not use a standard library function?". – P45 Imminent Jul 14 '15 at 16:18
  • That is what I am asking you actually! Is there a standard (good) way to do it, then show me and I will accept your answer. All the answers I see is dividing stuff and modulus etc... – JohnyTex Jul 14 '15 at 16:19