Problem with hours and minutes

0

hello with all I have the following code in java to capture the time and minutes, the code works, it returns me the time and the minutes of the system but, in hours and minutes less than 10 it returns me only a digit without including the zero to the left, please I need help to solve this detail. For example, it shows 9: 6, and I would like it to appear 09:06.

Calendar Cal = Calendar.getInstance();
    String fec = Cal.get(Cal.HOUR_OF_DAY) + ":" + Cal.get(Cal.MINUTE);
    txtHoraSalida.setText(fec);
    
asked by Eddy Trejo 05.09.2018 в 23:18
source

2 answers

1

You can use String.format for what you need:

Calendar cal = Calendar.getInstance();
String hour = String.format("%02d",cal.get(Calendar.HOUR_OF_DAY));
String minute = String.format("%02d",cal.get(Calendar.MINUTE));
String fec = hour + ":" + minute;
txtHoraSalida.setText(fec);

Note: Pay attention to the name of the variables, they are not capitalized.

Note 2: MINUTE and HOUR_OF_DAY are static, and should be accessed as such.

Example:

If we set the time manually, we can check the correct output.

    cal.set(Calendar.HOUR_OF_DAY, 5);
    cal.set(Calendar.MINUTE, 6);

Output: 05:06

    
answered by 06.09.2018 в 04:38
1

Use this code to format two digits.

 Calendar Cal = Calendar.getInstance();

 String time = String.format("%02d:%02d", Cal.get(Calendar.HOUR_OF_DAY), Cal.get(Calendar.MINUTE));

 txtHoraSalida.setText(time);
    
answered by 06.09.2018 в 04:39