How can I make a DateTimeFormatter that accepts trailing junk?

て烟熏妆下的殇ゞ 提交于 2020-01-21 06:51:54

问题


I'm retrofitting old some SimpleDateFormat code to use the new Java 8 DateTimeFormatter. SimpleDateFormat, and thus the old code, accepts strings with stuff in them after the date like "20130311nonsense". The DateTimeFormat I created throws a DateTimeParseException for these strings, which is probably the right thing to do, but I'd like to maintain compatibility. Can I modify my DateTimeFormat to accept these strings?

I'm currently creating it like this:

DateTimeFormatter.ofPattern("yyyyMMdd")

回答1:


Use the parse() method that takes a ParsePosition, as that one doesn't fail when it doesn't read the entire text:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

TemporalAccessor parse = formatter.parse("20140314 some extra text", new ParsePosition(0));
System.out.println(LocalDate.from(parse));

The ParsePosition instance that you pass will also be updated with the point at which the parsing stopped, so if you need to do something with the leftover text then it will be useful to assign it to a variable prior to calling parse.



来源:https://stackoverflow.com/questions/28998063/how-can-i-make-a-datetimeformatter-that-accepts-trailing-junk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!