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
SimpleDateFormatconstructor.java.timeAPI (e.g.Instant), why do you want to revert to the older and more error prone old one based onjava.util.Date(e.g.SimpleDateFormat) ?Instant answer = LocalDateTime .parse(date_time, DateTimeFormatter.ofPattern("M/d/uu h:mm a", Locale.ENGLISH)) .atZone(ZoneId.systemDefault()) .toInstant();. <in my time zone it gave anInstantof2024-01-10T18:00:00Z.