java.time
You apparently have a time-of-day without any date. The java.util.Date
class, despite its poorly chosen name, represents both a date and a time-of-day.
In Java 8 and later, the built-in java.time framework (Tutorial) offers a time-of-day class called LocalTime
. Just what you need for a time-only value.
If the hour may not have a padded leading zero, but the minute will, then I suggest simply prepending a zero when the length of input string is shorter.
String input = "834AM";
String s = null;
switch ( input.length () ) {
case 6:
s = input;
break;
case 5:
// Prepend a padded leading zero.
s = "0" + input;
break;
default:
// FIXME: Handle error condition. Unexpected input.
break;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "hhmma" );
LocalTime localTime = formatter.parse ( s , LocalTime :: from );
System.out.println ( "Input: " + input + " → s: " + s + " → localTime: " + localTime );
When run.
Input: 834AM → s: 0834AM → localTime: 08:34
If, on the other hand, a minute number below 10 will be a single digit without a padded leading zero, I have no solution. Seems to me that would be impossibly ambiguous. For example, does 123AM
mean 01:23AM
or 12:03AM
?
Tip: Stick with ISO 8601 formats, specifically 24-hour clock and leading zeros.