DateTimeFormatter在解析单位数部分时过于严格

Mac*_*iak 7 java parsing datetime-format java-8

我有一个格式MM/dd/yyyy,所以格式化的所有内容都是单个数字的前导ZERO.问题是,在分析我希望能够解析既"11/25/2018""5/25/2018",但格式应该总是返回前导零.

我试过ResolverStyle没有运气就尝试了不同的选择.

建立我自己的特定格式似乎是不合理的,当你认为它是开箱即用的SimpleDateFormat.

会欣赏任何想法,不涉及从头开始使用格式化程序 FormatterBuilder

Ḿűỻ*_*ṩ ᛗ 6

使用该M/d/yyyy格式,因为前导零将被忽略。MM/dd/yyyy意味着需要恰好两位数字,包括可能的前导零。

    DateTimeFormatter parseformat =
            DateTimeFormatter.ofPattern("M/d/yyyy");

    DateTimeFormatter outputformat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
Run Code Online (Sandbox Code Playgroud)

对于代码段

    String d1 = "1/1/2018";
    String d2 = "02/29/2016";
    String d3 = "4/01/2018";

    LocalDate date = LocalDate.parse(d1, parseformat);
    System.out.println(date.format(outputformat));
    date = LocalDate.parse(d2, parseformat);
    System.out.println(date.format(outputformat));
    date = LocalDate.parse(d3, parseformat);
    System.out.println(date.format(outputformat));
Run Code Online (Sandbox Code Playgroud)

我最终得到

01/01/2018
02/29/2016
04/01/2018
Run Code Online (Sandbox Code Playgroud)

正如预期的那样。

有关时间模式及其解析方式,请参阅SimpleDateFormat 文档;请注意,“模式字母通常会重复,因为它们的数量决定了确切的表示形式”,并且“对于解析,除非需要分隔两个相邻字段,否则模式字母的数量将被忽略”(此处分隔两个相邻字段)。


Leo*_*Aso 5

使用两种不同的格式M/d/yyyy进行解析和MM/dd/yyyy打印。前者将接受一位数和两位数的月份和天数,而后者将始终显示两位数,并在必要时加零。

SimpleDateFormat parseFormat = new SimpleDateFormat("M/d/yyyy");
SimpleDateFormat printFormat = new SimpleDateFormat("MM/dd/yyyy");

Date date1 = parseFormat.parse("4/5/2010");
Date date2 = parseFormat.parse("04/05/2010");
String output1 = printFormat.format(date1);
String output2 = printFormat.format(date2);
// output1 and output2 will be the same
Run Code Online (Sandbox Code Playgroud)


Deb*_*was 5

您可以使用appendOptional()Java 8时间API

DateTimeFormatter ALL_POSSIBLE_DATE_FORMAT = new DateTimeFormatterBuilder()
            .appendOptional(DateTimeFormatter.ofPattern("MM/dd/yyyy"))
            .appendOptional(DateTimeFormatter.ofPattern(("M/dd/yyyy")))
            .toFormatter();

System.out.println(LocalDate.parse("11/25/2018", ALL_POSSIBLE_DATE_FORMAT));
System.out.println(LocalDate.parse("5/25/2018", ALL_POSSIBLE_DATE_FORMAT));
Run Code Online (Sandbox Code Playgroud)

输出:

2018-11-25

2018-05-25