I've below java program which converts string to Instant object.
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
public class JenkinsBuildDateFormatApp {
public static void main(String[] args) {
String extractedDate = "Apr 25, 2024, 2:32:42 PM";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd, yyyy, h:mm:ss a");
TemporalAccessor ta = dtf.parse(extractedDate);
System.out.println(Instant.from(ta));
}
}
When I run the program, I get below error -
Exception in thread "main" java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: > {},ISO resolved to 2024-04-25T14:32:42 of type java.time.format.Parsed
at java.base/java.time.Instant.from(Instant.java:381)
at JenkinsBuildDateFormatApp.main(JenkinsBuildDateFormatApp.java:12)
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
at java.base/java.time.format.Parsed.getLong(Parsed.java:215)
at java.base/java.time.Instant.from(Instant.java:376)
... 1 more
Process finished with exit code 1
How can I resolve the error?
I'm posting this to show the essence of the above comments, which are almost entirely correct:
import java.util.Locale;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
public class JenkinsBuildDateFormatApp {
public static void main(String[] args) {
String extractedDate = "Apr 25, 2024, 2:32:42 PM";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd, yyyy, h:mm:ss a");
// Above question comments already show why it's necessary
// to give the Formatter these two attributes for the rest of the
// code to work (not that this is how one would necessarily *actually write* it)
dtf = dtf.withLocale(Locale.US).withZone(ZoneId.systemDefault());
TemporalAccessor ta = dtf.parse(extractedDate);
System.out.println(Instant.from(ta));
}
}