java - Elegant solution to parse date -
i want parse text date. however, there no guarantee text has desired format. may 2012-12-12
or 2012
or .
currently, down path nested try-catch blocks, that's not direction (i suppose).
localdate parse; try { parse = localdate.parse(record, datetimeformatter.ofpattern("uuuu/mm/dd")); } catch (datetimeparseexception e) { try { year year = year.parse(record); parse = localdate.from(year.atday(1)); } catch (datetimeparseexception e2) { try { // , on } catch (datetimeparseexception e3) {} } }
what's elegant solution problem? possible use optional
s absent in case exception happened during evaluation? if yes, how?
the datetimeformatterbuilder
class contains building blocks make work:
localdate = localdate.now(); datetimeformatter fmt = new datetimeformatterbuilder() .appendpattern("[uuuu[-mm[-dd]]]") .parsedefaulting(chronofield.year, now.getyear()) .parsedefaulting(chronofield.month_of_year, now.getmonthvalue()) .parsedefaulting(chronofield.day_of_month, now.getdayofmonth()) .toformatter(); system.out.println(localdate.parse("2015-06-30", fmt)); system.out.println(localdate.parse("2015-06", fmt)); system.out.println(localdate.parse("2015", fmt)); system.out.println(localdate.parse("", fmt));
the parsedefaulting()
method allows default value set specific field. in cases, localdate
can parsed result, because enough information available.
note use of "[...]" sections in pattern define optional.
Comments
Post a Comment