Rich
Rich

Reputation: 1635

Unable to obtain LocalDate from TemporalAccessor using quarters

I am trying to parse some date-string into a date value, however, using the below code, I am getting an exception:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("Q'Q'uuuu - MMM");

String d = "3Q2016 - Aug";
System.out.println(LocalDate.parse(d, formatter));

The exception is below

java.time.format.DateTimeParseException: Text '3Q2016 - Aug' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=8, QuarterOfYear=3, Year=2016},ISO of type java.time.format.Parsed

Looking at the exception, I see the correct data, but it is not able to be parsed for some reason.

Other similar topics i see suggest using LocalDate or LocalDateTime, but neither work.

Upvotes: 1

Views: 6927

Answers (3)

Holger
Holger

Reputation: 298539

As said in this answer, you need to specify a day to be able to parse to a LocalDate. So one solution is to parse to a YearMonth instead and convert to a LocalDate by specifying a day afterwards.

Or you create a DateTimeFormatter with a fixed day in the first place:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("Q'Q'uuuu - MMM")
    .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
    .toFormatter(Locale.US);
String d = "3Q2016 - Aug";
System.out.println(LocalDate.parse(d, formatter));

I used toFormatter(Locale.US) to make the example work in all environments. In an environment where the input string matches the current locale, you can use toFormatter() instead.

Upvotes: 4

Rahul R.
Rahul R.

Reputation: 92

Try adding a Time part to the date -

String str = "2Q1986 - Apr - 08 T00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("Q'Q'yyyy - MMM - dd 'T'hh:mm");
LocalDate dateTime = LocalDate.parse(str, formatter);

Upvotes: -1

Kiskae
Kiskae

Reputation: 25603

Its because the specified string does not have a specific date to select. You probably need to use YearMonth instead of LocalDateTime and then convert it using YearMonth.atDay(1) to get the first day of the month.

Upvotes: 6

Related Questions