how to parse a string of the format “MM.yyyy” in LocalDate

I am a bit put off by the analysis of the dates in Java 8 Time API.

Earlier I could easily write:

String date = "04.2013";
DateFormat df = new SimpleDateFormat("MM.yyyy");
Date d = df.parse(date);

But now if I use LocalDate and I do it like this:

String date = "04.2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yyyy");
LocalDate ld = LocalDate.parse(date, formatter);

I get an exception:

Java.time.format.DateTimeParseException: Text '04' could not be parsed at index 0
Java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.Java:1948)
Java.time.format.DateTimeFormatter.parse(DateTimeFormatter.Java:1850)
Java.time.LocalDate.parse(LocalDate.Java:400)
Java.time.LocalDate.parse(LocalDate.Java:385)
com.luxoft.ath.controllers.JsonController.region(JsonController.Java:38)
Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Java:62)
Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.Java:43)
Java.lang.reflect.Method.invoke(Method.Java:483)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.Java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.Java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.Java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.Java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.Java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.Java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.Java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.Java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.Java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.Java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.Java:617)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.Java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.Java:723)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.Java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)

If I change the format of the string to “yyyy-MM-dd” everything works perfectly, even without a formatter:

String date = "2013-04-12";
LocalDate ld = LocalDate.parse(date);

So my question is: how to parse date in custom format using Java 8 Time API?

Leave a comment