Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing date without month using DateTimeFormatter

I try to parse a date with this format: ddYYYY. For example, I have the string 141968, and I want to know that day = 14 and year = 1968.

I suppose I have to use directly a TemporalAccessor gave by DateTimeFormatter.parse(String), but I cannot find how to use this result. While debugging I see the result is a java.time.Parsed which is not public but contains informations I want in field fieldValues.

How can I parse this particular format?

Thank you.

like image 441
Happy Avatar asked Apr 15 '15 08:04

Happy


1 Answers

One approach is to default the missing month field:

DateTimeFormatter f = new DateTimeFormatterBuilder()
  .appendPattern("ddyyyy")
  .parseDefaulting(MONTH_OF_YEAR, 1)
  .toFormatter();
LocalDate date = LocalDate.parse("141968", f);
System.out.println(date.getDayOfMonth());
System.out.println(date.getYear());

Another is to query the TemporalAccessor:

DateTimeFormatter f = DateTimeFormatter.ofPattern("ddyyyy");
TemporalAccessor parsed = f.parse("141968");
System.out.println(parsed.get(ChronoField.YEAR));
System.out.println(parsed.get(ChronoField.DAY_OF_MONTH));

(Note the use of "y", not "Y" for parsing)

like image 93
JodaStephen Avatar answered Oct 04 '22 19:10

JodaStephen