Reputation: 93
I want to convert a String
of different forms to the Date
format. Here is my current code:
SimpleDateFormat sdf = new SimpleDateFormat("hhmma");
Date time = sdf.parse(string);
Testing it out, it will parse inputs such as 1030pm
correctly. However, it does not work on inputs like 830pm
or any other single digit hours. Is there any way around this? Or do I have to have a different DateFormat ("hmma")
for different String
lengths?
Upvotes: 3
Views: 250
Reputation: 340300
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.
Upvotes: 2