Search code examples
javadatesimpledateformat

Parse function unable to parse string and throwing error in Java


Not able to parse the following date. Getting parse exception. Please help in finding error :

            String myDate = "2020–03–01 3:15 pm";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm aa",Locale.ENGLISH);
            Date date = sdf.parse(myDate);

Solution

  • The separator character that you have used to separate the year, the month and the day doesn't seem to be correct. I suggest you type the date-time string again instead of copying and pasting it from somewhere. I also recommend you switch from the outdated date-time API to the modern one.

    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            String myDate = "2020-03-01 3:15 pm";
            DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                                .parseCaseInsensitive()
                                                .appendPattern("u-M-d h:m a")
                                                .toFormatter(Locale.ENGLISH);
            LocalDateTime ldt = LocalDateTime.parse(myDate, formatter);
            System.out.println(ldt);
        }
    }
    

    Output:

    2020-03-01T15:15
    

    If you still want to use the legacy date-time API, you can do it as follows:

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) throws ParseException {
            String myDate = "2020-03-01 3:15 pm";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm aa", Locale.ENGLISH);
            Date date = sdf.parse(myDate);
            System.out.println(date);
        }
    }
    

    Output:

    Sun Mar 01 15:15:00 GMT 2020
    

    Note that I've used a single h to match your date-time string.