0

I am trying to get the hour and minute value from a TimePicker View. When I use the code below I get the correct value, but if the minute value has a zero, for example the time 3:04, the below code will produce 3:4 instead of 3:04.

String time = viewTime.getCurrentHour()+":"+ viewTime.getCurrentMinute();
Drew Szurko
  • 1,601
  • 1
  • 16
  • 32
lifeishard
  • 17
  • 6
  • 1
    Just format minutes with leading zero – Selvin Feb 24 '17 at 01:34
  • Possible duplicate of [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) – Selvin Feb 24 '17 at 01:36

1 Answers1

1

One option here is to use String.format() with an appropriate mask to get two digit number strings for the hour and minute.

int hour = viewTime.getHour();
int minute = viewTime.getMinute;
String time = String.format("%02d:%02d", hour, minute);

Note that I have replaced your call to TimePicker#getCurrentHour() with TimePicker#getHour(), as the former has been deprecated since API level 23. Check the documentation for more information.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360