Akshat
Akshat

Reputation: 575

convert shortdate to LocalDate

Hi i have a short date format with me in the pattern E dd/MM , Is there any way i can convert it to LocalDate.

String date = "Thu 07/05";
String formatter = "E dd/MM"; 
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
final LocalDate localDate = LocalDate.parse(date, formatter);`

But it throws an exception java.time.format.DateTimeParseException: Text 'Thu 07/05' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=5, DayOfMonth=7, DayOfWeek=4},ISO of type java.time.format.Parsed

Is there any way we can fix this issue ?

Upvotes: 4

Views: 401

Answers (1)

assylias
assylias

Reputation: 328568

All you have is a month and a day - so you can create a MonthDay (to create a LocalDate you would also need a year):

MonthDay md = MonthDay.parse(date, formatter);

If you want a LocalDate, you can use the MonthDay as a starting point:

int year = Year.now().getValue();
LocalDate localDate = md.atYear(year);

Or alternatively you can use a default year in your formatter:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                        .appendPattern(pattern)
                                        .parseDefaulting(ChronoField.YEAR, year)
                                        .toFormatter(Locale.US);

LocalDate localDate = LocalDate.parse(date, formatter);

The benefit of this method is that it will also check that the day of week (Thursday) is correct.

Upvotes: 3

Related Questions