Parsing date without month using DateTimeFormatter

纵然是瞬间 提交于 2019-12-07 04:03:59

问题


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.


回答1:


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)




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/29644949/parsing-date-without-month-using-datetimeformatter

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