如何制作一个可以接受结尾垃圾的DateTimeFormatter? [英] How can I make a DateTimeFormatter that accepts trailing junk?

查看:94
本文介绍了如何制作一个可以接受结尾垃圾的DateTimeFormatter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对旧的某些SimpleDateFormat代码进行改装,以使用新的Java 8 DateTimeFormatter. SimpleDateFormat(因此是旧代码)接受日期之后的字符串,例如"20130311nonsense".我创建的DateTimeFormat会为这些字符串抛出DateTimeParseException,这也许是正确的做法,但我想保持兼容性.我可以修改我的DateTimeFormat接受这些字符串吗?

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")

推荐答案

使用

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));

您传递的ParsePosition实例也将以解析停止的位置进行更新,因此,如果您需要对剩余文本进行某些处理,则在调用<前将其分配给变量将非常有用. c9>.

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.

这篇关于如何制作一个可以接受结尾垃圾的DateTimeFormatter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆