I am looking to write a method that takes in a string of date time and can return an Instant . The string format can vary with different time formats as below, support for nano seconds to 8 places. I am not able to use a fixed format type due to this so my toInstant errors out when I give a format that does not confirm to the below. What would be the best approach to cater to all the different datetime formats below?
The format of the date time can be in different formats:
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss.S
yyyy-MM-dd HH:mm:ss.SSSSSSSS
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.of("UTC"));
return Instant.from(formatter.parse(timeStr));
}