Reputation: 655
I have two int variables as follows:
int minutes = 20;
int hours = 8;
How do I want to convert them to "HHMM" formation?
For the above, the result should be "0820".
Upvotes: 2
Views: 8719
Reputation: 3630
If you only want to display "0820" you can just paste them together in a string.
String hoursMinutes = String.format("%02d", hours) + String.format("%02d", minutes);
Upvotes: 0
Reputation: 1626
Looks like you want it in a string which is simple. Just append them to a string.
String time = String.valueOf(hours) + String.valueOf(minutes);
if (hours < 10)
time = "0" +time;
Upvotes: 0
Reputation: 55589
If you just want to pad the variables to 2 digits each:
int minutes = 20;
int hours = 8;
String str = String.format("%02d%02d", hours, minutes);
System.out.println(str);
Prints:
0820
Look at this for more details.
Upvotes: 8
Reputation: 4239
Use Calendar
class as below:
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, hours);
c.set(Calender.MINUTE, minutes);
In case you only want to format the values, you can use:
String str = String.format("%02d%02d", hours, minutes);
Upvotes: 6