I write applications for hours.

There are variable int hour=1 and int min=9 .

How to transfer such numbers to "01" and "09" into int or immediately string for subsequent sending via bluetooth.

  • How do you bring them to String ? And why think you are doing it wrong? - Regent
  • I have the option to translate the number into string, then if (string.lench == 1) {sting = "0" + string}. And I'm wondering if there is a better way - Walker

2 answers 2

If you abstract from the fact that it is hours and minutes, then you can think of it as formatting the output of a number.

In this case, you can use the String.format method:

 String result = String.format("%02d", hour); 

The decision "head on" for a specific situation from the question, in my opinion, also has the right to life, because it is understandable, short and works at least not slowly:

 String result = hour < 10 ? "0" + hour : "" + hour; 

When using the old version of Java, it generally becomes basic. For Android, such old versions are irrelevant, but still.

    Use SimpleDateFormat :

     Calendar calendar = Calendar.getInstance(); String hours = new SimpleDateFormat("HH").format(calendar.getTime()); String minutes = new SimpleDateFormat("mm").format(calendar.getTime()); 

    "HH" (and "mm") are responsible for ensuring that the numbers are displayed two-digit (even if they are less than 10).

    Look here for more detail. There are other formats for displaying dates.