Java 8 Time API:如何将格式“MM.yyyy”的字符串解析为LocalDate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23800477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 Time API: how to parse string of format "MM.yyyy" to LocalDate
提问by Maxim Kolesnikov
I'm a bit discouraged with parsing dates in Java 8 Time API.
我对在Java 8 Time API 中解析日期感到有点气馁。
Previously I could easily write:
以前我可以很容易地写:
String date = "04.2013";
DateFormat df = new SimpleDateFormat("MM.yyyy");
Date d = df.parse(date);
But now if I use LocalDateand do it like this:
但是现在如果我使用LocalDate并这样做:
String date = "04.2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yyyy");
LocalDate ld = LocalDate.parse(date, formatter);
I receive 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 string format to "yyyy-MM-dd"everything work perfectly, even without formatter:
如果我将字符串格式更改为"yyyy-MM-dd"一切正常,即使没有格式化程序:
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?
所以我的问题是:如何使用 Java 8 Time API 以自定义格式解析日期?
采纳答案by assylias
It makes sense: your input is not really a date because it does not have a day information. You should parse it as a YearMonth
and use that result if you don't care about the day.
这是有道理的:您的输入并不是真正的日期,因为它没有日期信息。YearMonth
如果您不关心这一天,您应该将其解析为 a并使用该结果。
String date = "04.2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yyyy");
YearMonth ym = YearMonth.parse(date, formatter);
If you do need to apply a specific day, you can obtain a LocalDate
from a YearMonth
for example:
如果您确实需要应用特定的日期,您可以LocalDate
从YearMonth
例如获取 a :
LocalDate ld = ym.atDay(1);
//or
LocalDate ld = ym.atEndOfMonth();
You can also use a TemporalAdjuster
, for example, for the last day of the month*:
TemporalAdjuster
例如,您还可以将用于每月的最后一天*:
LocalDate ld = ym.atDay(1).with(lastDayOfMonth());
*with an import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
*带着 import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
回答by Meno Hochschild
Following alternative is probably not so nice but at least a successfully tested solution, too, so I mention it here for completeness and as supplement to the right answer of @assylias:
以下替代方案可能不是那么好,但至少也是一个成功测试的解决方案,所以我在这里提到它是为了完整性并作为对@assylias 正确答案的补充:
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseDefaulting(ChronoField.DAY_OF_MONTH, 1);
builder.append(DateTimeFormatter.ofPattern("MM.yyyy"));
DateTimeFormatter dtf = builder.toFormatter();
String ym = "04.2013";
LocalDate date = LocalDate.parse(ym, dtf);
System.out.println(date); // output: 2013-04-01