[英]Parsing date without month using DateTimeFormatter
我嘗試用這種格式解析日期: ddYYYY
。 例如,我有字符串141968
,我想知道day = 14
和year = 1968
。
我想我必須直接使用DateTimeFormatter.parse(String)
給出的TemporalAccessor
,但是我找不到如何使用這個結果。 在調試時我看到結果是java.time.Parsed
,它不是公共的,但在字段fieldValues
包含我想要的信息。
我該如何解析這種特殊格式?
謝謝。
一種方法是默認缺少的月份字段:
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”進行解析)
YYYY
生成一個WeakBasedYear字段,無法從TemporalAccessor
輕松訪問( https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns )。 你必須使用模式“ddyyyy”或“dduuuu”與DateTimeFormatter
使用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));
輸出:
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));
輸出14/1968
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.