Reputation: 305
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.
Upvotes: 3
Views: 3071
Reputation: 109124
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).
Upvotes: 2
Reputation: 321
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;
}
Upvotes: 0