使用DateTimeFormatter解析没有月份的日期 [英] Parsing date without month using DateTimeFormatter

查看:905
本文介绍了使用DateTimeFormatter解析没有月份的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下格式解析日期: ddYYYY 。例如,我有字符串 141968 ,我想知道 day = 14 year = 1968

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.

我想我必须直接使用 TemporalAccessor 给出通过 DateTimeFormatter.parse(String),但我找不到如何使用此结果。在调试时,我看到结果是 java.time.Parsed ,它不是公共的,但在字段中包含我想要的信息 fieldValues

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?

谢谢。

推荐答案

一种方法是默认失踪月份字段:

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

另一种是查询 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));

(注意使用y而不是Y进行解析)

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

这篇关于使用DateTimeFormatter解析没有月份的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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