java - Parse nano seconds with less than 6 digits -
i have timestamp 2017-07-25 16:19:59.89384
i want parse with:
datetimeformatter formatter = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss.ssssss"); localdate time = localdatetime.parse(timestamp, formatter);
but datetimeparseexception
because nano seconds 5 digits. there cleaner solution padding 0
's right?
if input always has 5 digits in nanoseconds, can use 5 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"); // 5 "s" localdatetime datetime = localdatetime.parse(timestamp, formatter);
also note localdatetime.parse
returns localdatetime
(not localdate
in code).
if don't know how many digits in input, can use java.time.format.datetimeformatterbuilder
java.time.temporal.chronofield
, define minimum , maximum number of digits:
datetimeformatter formatter = new datetimeformatterbuilder() // date / time .appendpattern("yyyy-mm-dd hh:mm:ss") // nanoseconds, minimum 1 , maximum 9 digits , decimal point .appendfraction(chronofield.nano_of_second, 1, 9, true) // create formatter .toformatter(); localdatetime datetime = localdatetime.parse(timestamp, formatter);
you need adjust values 1 , 9 according needs.
Comments
Post a Comment