Parsing date without month using DateTimeFormatter

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 07:30:38

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)

YYYY produces a WeakBasedYear field which cannot be accessed that easily (https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns) from TemporalAccessor. You have to use the pattern "ddyyyy" or "dduuuu" with DateTimeFormatter to use ChronoField.YEAR:

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

Output:

1968
14

SimpleDateFormat sdf = new SimpleDateFormat("ddyyyy");
Date DateToStr = sdf.parse("141968");// To convert to date Date object
sdf = new SimpleDateFormat("dd/yyyy"); // Separating by '/'
System.out.println(sdf.format(DateToStr));

output 14/1968

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