2

I am trying to create an object of the Java class LocalTime like this:

LocalTime beginning = LocalTime.of(int hours, int minutes);

My problem is that I would like that my user could input the time in the following format: HH:MM However, when there's an input like 14:00 as String, I replace the ":" by "".

Then I say:

hours = Integer.parseInt(eingabe.substring(0, 2));
minutes = Integer.parseInt(eingabe.substring(2));

But now minutes is 0 and not 00 like I want it to. I've done some research and found something like String.format("%02d", minutes), but the parameters of LocalTime.of() needs to be integers.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
CWhite
  • 185
  • 2
  • 3
  • 9
  • hours and minutes can be stored as int, meaning that 0 is not 00. You only need that for an output, in that case, you can use the `String.format("%02d", minutes)` to get the string for the output, like you already researched. – Alex Jan 29 '17 at 13:19
  • Thank you I also found out that the to.String() method gets me the output, which I wanted. – CWhite Jan 29 '17 at 13:29
  • @CWhite that's not `to.String` , that is `.toString();` – Mohsen_Fatemi Jan 29 '17 at 13:35
  • Excuse me, thats what I meant – CWhite Jan 29 '17 at 13:36

2 Answers2

2

If you have an input like 14:00 you don't need to do manual formatting, instead you can use java.time.format.DateTimeFormatter:

String input = "14:00";
DateTimeFormatter simpleTime = DateTimeFormatter.ofPattern("HH:mm");
LocalTime localtime = LocalTime.parse(input, simpleTime);

However your original problem was not a problem to begin with. The "00" in "14:00" is just formatting, it does not mean that the integer value of the minutes is 00: it is 0; it is just displayed as "00" to be less confusing for people viewing the time (eg it is hard to distinguish 14:1 from 14:10 etc).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
0

You can not get a int with double zero because it is an integer value, the only way to get a double zero is formatting your LocalTime to String. There are different ways to do this and it depends in the Date API that your are using. Seeing your classes I assume that your are using JodaTime, so my example will be focused to this API, so, to format your object, you can do this:

public static String toTimeString(LocalTime source) {

    try {
        return source.toString("HH.mm");
    } catch (Exception ignored) {
    }

    return null;
}
Gabriel Villacis
  • 331
  • 7
  • 17