ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

具有可选模式的Java DateTimeFormatterBuilder导致DateTimeParseException

2019-07-31 05:00:12  阅读:326  来源: 互联网

标签:java datetime-format


目标

为LocalDate实例提供灵活的解析器,可以使用以下格式之一处理输入:

> yyyy
> yyyyMM
> yyyyMMdd

实施尝试

以下类尝试处理第一个和第二个模式.解析工作年份输入,但年月导致下面列出的例外情况.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;

public class DateTest {

    public static void main(String[] args) {
        DateTimeFormatter parser = new DateTimeFormatterBuilder()
        .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
        .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
        .appendPattern("yyyy")
        .optionalStart().appendPattern("MM").optionalEnd().toFormatter();

        System.out.println(parser.parse("2014", LocalDate::from)); // Works
        System.out.println(parser.parse("201411", LocalDate::from)); // Fails
    }
}

第二次parse()尝试导致以下异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text '201411' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)

我认为我对可选部分模式如何工作的理解是缺乏的.我的目标是一个灵活格式的解析器甚至可以实现,还是我需要检查输入长度并从解析器列表中选择?一如既往,感谢帮助.

解决方法:

问题的真正原因是签名处理.您的输入没有任何符号,但解析器元素“yyyy”贪婪地解析尽可能多的数字并期望正号,因为找到了超过四位数.

我的分析以两种不同的方式完成:

>调试(以查看不明确的错误消息背后的真实情况)
>基于我的lib Time4J模拟另一个解析引擎中的行为,以获得更好的错误消息:

ChronoFormatter<LocalDate> cf =
ChronoFormatter
    .ofPattern(
        "yyyy[MM]",
        PatternType.THREETEN,
        Locale.ROOT,
        PlainDate.axis(TemporalType.LOCAL_DATE)
    )
    .withDefault(PlainDate.MONTH_AS_NUMBER, 1)
    .withDefault(PlainDate.DAY_OF_MONTH, 1)
    .with(Leniency.STRICT);
System.out.println(cf.parse("201411")); 
// java.text.ParseException: Positive sign must be present for big number.

您可以通过指示构建器始终仅使用年份的四位数来规避问题:

DateTimeFormatter parser =
    new DateTimeFormatterBuilder()
        .appendValue(ChronoField.YEAR, 4)
        .optionalStart()
        .appendPattern("MM[dd]")
        .optionalEnd()
        .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
        .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
        .toFormatter();

System.out.println(parser.parse("2014", LocalDate::from)); // 2014-01-01
System.out.println(parser.parse("201411", LocalDate::from)); // 2014-11-01
System.out.println(parser.parse("20141130", LocalDate::from)); // 2014-11-30

注意构建器中默认元素的位置.它们不是在开始时调用,而是在最后调用,因为不幸的是,在java.time中对默认元素的处理是位置敏感的.我还在第一个可选部分的内部添加了一个额外的可选部分.这个解决方案对我来说似乎更干净,而不是像Danila Zharenkov建议的那样使用3个可选部分的序列,因为后者也可以用更多的数字来解析相当不同的输入(可能滥用可选部分作为替换or-patterns特别是在宽松中解析).

关于默认元素的位置敏感行为,这里引用了API-documentation

During parsing, the current state of the parse is inspected. If the
specified field has no associated value, because it has not been
parsed successfully at that point, then the specified value is
injected into the parse result. Injection is immediate, thus the
field-value pair will be visible to any subsequent elements in the
formatter. As such, this method is normally called at the end of the
builder.

顺便说一句:在我的lib Time4J中,我还可以使用符号“|”定义真实或模式然后创建此格式化程序:

ChronoFormatter<LocalDate> cf =
    ChronoFormatter
        .ofPattern(
            "yyyyMMdd|yyyyMM|yyyy",
            PatternType.CLDR,
            Locale.ROOT,
            PlainDate.axis(TemporalType.LOCAL_DATE)
        )
        .withDefault(PlainDate.MONTH_AS_NUMBER, 1)
        .withDefault(PlainDate.DAY_OF_MONTH, 1)
        .with(Leniency.STRICT);

标签:java,datetime-format
来源: https://codeday.me/bug/20190731/1587440.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有