Java: Unable to obtain LocalDate from TemporalAccessor -
i trying change format of string date eeee mmmm d mm/d/yyyy by, first, converting localdate , applying formatter of different pattern localdate before parsing string again.
here's code:
private string convertdate(string stringdate) { //from eeee mmmm d -> mm/dd/yyyy datetimeformatter formatter = new datetimeformatterbuilder() .parsecaseinsensitive() .append(datetimeformatter.ofpattern("eeee mmmm d")) .toformatter(); localdate parseddate = localdate.parse(stringdate, formatter); datetimeformatter formatter2 = datetimeformatter.ofpattern("mm/d/yyyy"); string formattedstringdate = parseddate.format(formatter2); return formattedstringdate; } however, exception message don't understand:
exception in thread "main" java.time.format.datetimeparseexception: text 'tuesday july 25' not parsed: unable obtain localdate temporalaccessor: {dayofweek=2, monthofyear=7, dayofmonth=25},iso of type java.time.format.parsed @ java.time.format.datetimeformatter.createerror(datetimeformatter.java:1920)
as other answers said, create localdate need year, not in input string. has day, month , day of week.
to full localdate, need parse day , month , find year in day/month combination matches day of week.
of course ignore day of week , assume date in current year; in case, other answers provided solution. if want find year matches day of week, must loop until find it.
i'm creating formatter java.util.locale, make explicit want month , day of week names in english. if don't specify locale, uses system's default, , it's not guaranteed english (and can changed without notice, @ runtime).
datetimeformatter formatter = new datetimeformatterbuilder() .parsecaseinsensitive() .append(datetimeformatter.ofpattern("eeee mmmm d")) // use english locale correctly parse month , day of week .toformatter(locale.english); // parse input temporalaccessor parsed = formatter.parse("tuesday july 25"); // month , day monthday md = monthday.from(parsed); // day of week dayofweek dow = dayofweek.from(parsed); localdate date; // start arbitrary year, stop @ arbitrary value for(int year = 2017; year > 1970; year--) { // day , month @ year date = md.atyear(year); // check if day of week same if (date.getdayofweek() == dow) { // found: 'date' correct localdate break; } } in example, started @ year 2017 , tried find date until 1970, can adapt values fits use cases.
you can current year (instead of fixed arbitrary value) using year.now().getvalue().
Comments
Post a Comment