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 line from question 01:19 PM into LocalTime equal to 13:19 .
We still need to provide the locale. Since the AM / PM markers are practically not used in practice in other locations than English, I considered Locale.ENGLISH fairly safe bet. Please replace yours.
When this question was asked in 2014, there was no modern replacement for the old Date and SimpleDateFormat classes, the modern Java date and time API. Today I believe that the old classes are long outdated and warmly recommend the use of modern ones. As a rule, they showed that they are more convenient in programming and convenient in work.
Just for one simple thing, if we cannot give a locale on a system with a default locale that does not 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, where he says PM , was already on our way. Yes, I know that there is a way to get the index from an exception thrown by an obsolete class, but most programmers never knew and therefore did not use it.
More importantly, the new API offers the LocalTime class, which gives us what we want and need here: just the time of day without a date. This allows us to more accurately model our data. There are a number of stack overflow issues caused by confusion, which in turn is caused by the fact that Date necessarily includes both a date and a time when sometimes you only want one or the other.
source share