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);
}
The
java.utildate-time API and their corresponding parsing/formatting type,SimpleDateFormatare 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 tojava.time, the modern date-time API.The given date-time string does not have time zone information; therefore, parse it into a
LocalDateTimeand then apply the system-default time-zone to convert it into aZonedDateTime. Finally, convert theZonedDateTimeinto anInstant.Demo:
Output:
ONLINE DEMO
Note that you can use
Instant#parseonly for those strings which conform toDateTimeFormatter.ISO_INSTANTe.g.Instant.parse("2011-12-03T10:15:30Z").Learn about the modern date-time API from Trail: Date Time