Search code examples
javadatedate-conversion

Format date with random number of split seconds


I need to parse a string to date. The problem is that the string has a random number of split seconds. To be more precise the number of digits vary between 0 and 7. To test this i wrote the following scenario:

public static void main(String[] args) throws ParseException {
    // printDate("2016-02-10T12:48:08.632746Z");
    printDate("2016-02-10T12:48:08.632Z");

}

private static void printDate(String datumAsString) throws ParseException {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    System.out.println(LocalDateTime.parse(datumAsString, formatter));
}

The commented line does not work (it throws a ParseException). Do you have any idea how to solve this?


Solution

  • Assuming that the digits after the seconds represent a fraction of second and not a number of milliseconds, both strings can be parse "natively" by ZonedDateTime - so you could write:

    private static void printDate(String datumAsString) throws ParseException {
      LocalDateTime ldt = ZonedDateTime.parse(datumAsString).toLocalDateTime(); 
      System.out.println(ldt);
    }
    

    You may also want to stick with a ZonedDateTime instead of ignoring the time zone information.