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 optionals 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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -