LocalTime
Modern answer using LocalTime
class.
LocalTime time = null;
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
try {
time = LocalTime.parse(s, parseFormatter);
} catch (DateTimeParseException dtpe) {
System.out.println(dtpe.getMessage());
}
This turns the string from the question, 01:19 PM
, into a LocalTime
equal to 13:19
.
We still need to provide the locale. Since AM/PM markers are hardly used in practice in other locales than English, I considered Locale.ENGLISH
a fairly safe bet. Please substitute your own.
Already when this question was asked in 2014, the modern replacement for the old classes Date
and SimpleDateFormat
was out, the modern Java date and time API. Today I consider the old classes long outdated and warmly recommend using the modern ones instead. They have generally shown to be remarkably more programmer friendly and convenient to work with.
Just for one simple little thing, if we fail to give a locale on a system with a default locale that doesn’t recognize AM and PM, the modern formatter will give us an exception with the message Text '01:19 PM' could not be parsed at index 6
. Index 6 is where it says PM
, so we’re already on our way. Yes, I know there is a way to get the index out of the exception thrown by the outdated class, but the majority of programmers were never aware and hence did not use it.
More importantly, the new API offers a class LocalTime
that gives us what we want and need here: just the time-of-day without the date. This allows us to model our data much more precisely. There are a number of questions on Stack Overflow caused by confusion in turn caused by the fact that a Date
necessarily includes both date and time when sometimes you want only one or the other.