Is there a way to force a single digit Int into a two digit int value?

748 Views Asked by At

I need to show time in my app. i am storing the hour and minutes values in the form of integer to the database. all works fine, but I dislike it when a value drops to a single digit as it is meant to look like a 4 value clock. By this I mean, if the time is 6 hours and 3 minutes it outputs "6:3" when if it is 11 hours and 11 minutes it outputs"11:11". I would like it to always display 4 numbers regardless of the value.

WHAT HAPPENS :

6:3 AM (6 hours 3 minutes)

11:11 AM (11 hours 11 minutes)

WHAT I WANT

6:03 AM (6 hours 3 minutes)

4:08 PM ( 4 hour 8 minutes )

11:11 AM (11 hours 11 minutes)

Thank you.

2

There are 2 best solutions below

0
laalto On

What you're looking for is String formatting.

For example, String.format("%02d", minutes) to format minutes as integer with 2 digits, left-padding with zeros as necessary.

1
JunaidKhan On
private String getMinutesInTwoDigits(String time) {
    SimpleDateFormat dateFormatGiven = new SimpleDateFormat("h:m a");
    SimpleDateFormat dateFormatRequired = new SimpleDateFormat("h:mm a");
    String result = null;
    try {
        result = dateFormatRequired.format(dateFormatGiven.parse(time));
    } catch (ParseException e) {
        return time;
    }
    return result;
}