0

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));
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
serah
  • 2,057
  • 7
  • 36
  • 56
  • 2
    Each format has different length, can't you check the length of `timeStr` and set the correct pattern in a `switch` depending on the length? – Joakim Danielson May 09 '19 at 07:14
  • 1
    Or you can try to use a `DateTimeFormatterBuilder`, and define an optional pattern. – MC Emperor May 09 '19 at 07:16
  • 1
    None of those inputs describes an `Instant` because they lack an indicator of time zone or offset-from-UTC. The appropriate class is `LocalDateTime`, except `LocalDate` for the first. – Basil Bourque May 09 '19 at 07:20
  • @megan This question is marked as duplicate, but the accepted answer of the linked question uses the old date and time classes, like `SimpleDateFormat` and `Date`. [These are bad](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api). – MC Emperor May 09 '19 at 07:36

0 Answers0