Search code examples
javastringbuilder

Individually available Hour Minute Seconds to HH:mm:ss format


I have an object which stores hour, minute, seconds individually.

public static class ETA {
        private int hours;  // 2 (single or double digit 24 hour format)
        private int minutes; // 0 (single or double digit)
        private int seconds;  // 0 (single or double digit)

// getters.. setters..
}

I need to save this time into a csv file with proper string as "02:00:00" with format of HH:mm:ss and NOT as "2:0:0";

I tried with StringBuilder append() method, but came up with very messed code. Here's what I tried...

ETA e = new ETA();
StringBuilder time = new StringBuilder();
if (e.getHour() < 10) {
time.append("0" + e.getHour());
} else {
time.append(e.getHour());
}
// similarly for minute and seconds, and then returned time.

It doesn't seem nice to me. So How should I approach it in a better way?


Solution

  • Something like this:

    String.format("%02d:%02d:%02d", e.getHours(), e.getMinutes(), e.getSeconds())