Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a DateTimeFormatter that accepts trailing junk?

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")
like image 812
Samuel Edwin Ward Avatar asked Mar 11 '15 21:03

Samuel Edwin Ward


People also ask

What is the difference between DateTimeFormatter and SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

What is DateTimeFormatter Iso_date_time?

static DateTimeFormatter. ISO_DATE_TIME. The ISO-like date-time formatter that formats or parses a date-time with the offset and zone if available, such as '2011-12-03T10:15:30', '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.

How do I use DateTimeFormatter with date?

DateTimeFormatter fmt = DateTimeFormatter. ofPattern("yyyy-MM-dd'T'HH:mm:ss"); System. out. println(ldt.

What is the use of DateTimeFormatter?

The main API for dates, times, instants, and durations. Generic API for calendar systems other than the default ISO. Provides classes to print and parse dates and times.


1 Answers

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.

like image 96
bowmore Avatar answered Oct 26 '22 01:10

bowmore