Parse nano seconds with less than 6 characters
I have a time stamp 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 am getting DateTimeParseException
because nano seconds are only 5 digits. Is there a cleaner solution than 0
right padding ?
source to share
If the input always has 5 digits in nanoseconds, you can use five letters S
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 what LocalDateTime.parse
returns LocalDateTime
(and not LocalDate
as in your code).
If you don't know how many digits the input will be, you can use java.time.format.DateTimeFormatterBuilder
with 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.