String timeString = "10:10";
LocalTime time = LocalTime.parse(timeString);
System.out.println(time);
This prints
10:10
I am cheating a bit, though. The way I read your question, you asked for a date-time object with the format HH:mm
in it. Neither a LocalTime
object (used in the above snippet) nor a Date
(used in your code) can have a format in it. What you get when you concatenate the Date
to a string or print the LocalTime
is the result of the object’s toString
method, and you cannot change this method (only in subclasses, and you don’t want that). In other words, when you want a specific format, you need to have that format in a string outside the date-time object.
The lucky part is that LocalTime.toString()
produces the format you want (as long as the seconds and fraction of second are zero; otherwise they would be in the string too).
Will that work on your Android device? It will. LocalTime
is a class of JSR-310 also known as java.time
, the modern Java date and time API introduced nearly 4 years ago, early in 2014. JSR-310 has been backported to Java 6 and 7 in ThreeTen Backport, which in turn has been adapted to Android in ThreeTenABP. So get ThreeTenABP, add it to your project and start enjoying how much nicer it is to work with than the outdated date and time classes.
PS There’s a bug in your format pattern string in the question: Lowercase hh
is for hour within AM or PM from 1 through 12, which works nicely when the hours are 10, but not always. I am convinced that you want uppercase HH
for hour of day in the interval 0 through 23. When I run your code with a string of 12:12
, I get Thu Jan 01 00:12:00 CET 1970. The hours are 0, not 12.
Links