Search code examples
androidtimepicker

Android Time Picker getting correct value from TimePicker


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();

Solution

  • 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.