Search code examples
javasimpledateformat

What's the correct date format for this case?


I've been trying to parse String into Date, But, The conversion isn't working.

For example, I've these Strings, retrieved from a webservice.

Dec 9, 2016 4:36:00 PM
Jan 12, 2017 11:36:15 AM

I've tried to use these formats, But, The conversion failed.

MMM d, yyyy HH:mm:ss aaa
MMM d, yyyy hh:mm:ss a

Where am I wrong?

I'm getting this exception
java.text.ParseException: Unparseable date: "Dec 9, 2016 4:36:00 PM"


Solution

  • This is just a variation of the @C.P.O answer and uses a slightly different pattern.

    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    import org.junit.Test;
    
    public class blam
    {
        private static final String VALUE1 = "Dec 9, 2016 4:36:00 PM";
        private static final String VALUE2 = "Jan 12, 2017 11:36:15 AM";
    
        @Test
        public void test()
        {
            DateTimeFormatter dateTimeFormatter;
            LocalDateTime value;
    
            dateTimeFormatter = DateTimeFormatter.ofPattern("MMM d, u h:m:s a");
    
            value = LocalDateTime.parse(VALUE1, dateTimeFormatter);
            System.out.println("value1. " + VALUE1 + " becomes: " + value);
    
    
            value = LocalDateTime.parse(VALUE2, dateTimeFormatter);
            System.out.println("value2. " + VALUE2 + " becomes: " + value);
        }
    }
    

    Some notes:

    • y is "year of era"
    • u is "year"
    • MMM is required. Neither "M" nor "MM" will work in your case.
    • I prefer "s" to "ss" because "s" will parse both 2 and 12, but "ss" will fail to parse "2"

    I don't know the real impact of using 'y' instead of 'u'.