Convert shortdate to LocalDate

Hi, I have a short date format with me in the E dd / MM template, 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

Can this problem be fixed?

+4
source share
1 answer

You have a month and a day, so you can create a MonthDay (you will also need a year to create a LocalDate):

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

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

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

Or, alternatively, you can use the default year in your formatting:

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

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

The advantage of this method is that it also checks for the correct day of the week (Thursday).

+3

Source: https://habr.com/ru/post/1621608/


All Articles