3

I have the Timestamp 2017-07-25 16:19:59.89384

I want to parse it with:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
LocalDate time = LocalDateTime.parse(timeStamp, formatter);

But I get a DateTimeParseException because the nano seconds are only 5 digits. Is there a cleaner solution than padding 0's to the right?

MaxPower
  • 881
  • 1
  • 8
  • 25
  • 1
    suppose this [post](https://stackoverflow.com/questions/30135025/java-date-parsing-with-microsecond-or-nanosecond-accuracy) may be helpful to you find a formatter for displaly nano seconds. – Rajith Pemabandu Jul 25 '17 at 23:31
  • 1
    I believe one option is `timeStamp = timeStamp.replace(' ', 'T');` and then use the one-arg `LocalDateTime.parse(CharSequence)`. Personally I prefer [Hugo’s solution](https://stackoverflow.com/a/45315209/5772882), but it’s much a matter of taste. – Ole V.V. Jul 26 '17 at 00:06

2 Answers2

4

If the input always has 5 digits in nanoseconds, you can use five S letters instead of six:

String timeStamp = "2017-07-25 16:19:59.89384";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSS"); // five "S"
LocalDateTime datetime = LocalDateTime.parse(timeStamp, formatter);

Also note that LocalDateTime.parse returns a LocalDateTime (not a LocalDate like in your code).


If you don't know how many digits will be in the input, you can use a java.time.format.DateTimeFormatterBuilder with a java.time.temporal.ChronoField and define the minimum and maximum number of digits:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // date / time
    .appendPattern("yyyy-MM-dd HH:mm:ss")
    // nanoseconds, with minimum 1 and maximum 9 digits and a decimal point
    .appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
    // create formatter
    .toFormatter();
LocalDateTime datetime = LocalDateTime.parse(timeStamp, formatter);

You just need to adjust the values 1 and 9 according to your needs.

3
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.n");
SChristy
  • 31
  • 1