javasimpledateformatdatetime-parsing

I got the error "java.text.ParseException: Unparseable date: "1/10/24 7:00 PM"" when trying to parse


I have a date string as "1/10/24 7:00 PM" (10th Jan.2024). How to parse it using SimpleDateFormat?

String date_time = "1/10/24 7:00 PM";
Instant answer;
try {
    answer = Instant.parse(date_time);
} catch(DateTimeParseException ex) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    answer = simpleDateFormat.parse(date_time).toInstant();
    System.out.println(answer);
}

Solution

  • I have a date string as "1/10/24 7:00 PM" (10th Jan.2024). How to parse it using SimpleDateFormat?

    The java.util date-time API and their corresponding parsing/formatting type, SimpleDateFormat are outdated and error-prone. In March 2014, the modern Date-Time API supplanted the legacy date-time API. Since then, it has been strongly recommended to switch to java.time, the modern date-time API.

    The given date-time string does not have time zone information; therefore, parse it into a LocalDateTime and then apply the system-default time-zone to convert it into a ZonedDateTime. Finally, convert the ZonedDateTime into an Instant.

    Demo:

    public class Main {
        public static void main(String[] args) {
            String strDateTime = "1/10/24 7:00 PM";
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uu h:mm a", Locale.ENGLISH);
            LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
            ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
            Instant output = zdt.toInstant();
            System.out.println(output);
        }
    }
    

    Output:

    2024-01-10T19:00:00Z
    

    ONLINE DEMO

    Note that you can use Instant#parse only for those strings which conform to DateTimeFormatter.ISO_INSTANT e.g. Instant.parse("2011-12-03T10:15:30Z").

    Learn about the modern date-time API from Trail: Date Time