3

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?

5
  • If I tried hmma, 830pm would work just fine. But 1030pm will give me a parse exception. Commented Oct 16, 2015 at 11:02
  • I can only think of kludges, like pre-pending a 0 to the String if length is inadequate. Let's see what answers pop up. 1+ Commented Oct 16, 2015 at 11:15
  • Allow only Dates with length of 6 chars and adding a '0' to ypur String so that every String has to look like 1122pm, 0122pm, 0102pm Commented Oct 16, 2015 at 11:18
  • stackoverflow.com/a/3618809/4088809 maybe ? Commented Oct 16, 2015 at 13:20
  • What about the minute-of-hour number, will it be padded with a leading zero or not? For example, is 01:02 AM going to be 12AM or 102AM? Commented Oct 17, 2015 at 6:08

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.