Java DateTimeFormatter 支持单位数的月份和月份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27571377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:36:58  来源:igfitidea点击:

DateTimeFormatter Support for Single Digit Day of Month and Month of Year

javadatejava-8java-time

提问by Mark Maxey

DateTimeFormmaterdoesn't seem to handle single digit day of the month:

DateTimeFormmater似乎不能处理一个月中的个位数:

String format = "MM/dd/yyyy";
String date   = "5/3/1969";
System.out.println(new SimpleDateFormat(format).parse(date));
System.out.println(LocalDate.parse(date, DateTimeFormatter.ofPattern(format)));

In this example, SimpleDateFormatcorrectly parses the date, but DateTimeFormatterthrows an exception. If I were to use zero padded dates, e.g., "05/03/1969", both work. However, if either the day of month or the month of year are single digit, then DateTimeFormatterthrows an exception.

在本例中,SimpleDateFormat正确解析日期,但DateTimeFormatter抛出异常。如果我要使用零填充日期,例如“05/03/1969”,两者都有效。但是,如果月份中的某一天或年份中的月份是个位数,则DateTimeFormatter抛出异常。

What is the right DateTimeFormatterformat to parse both one and two digit day of month and month of year?

DateTimeFormatter解析月份和月份的一位数和两位数的日期的正确格式是什么?

回答by Holger

From the documentation:

文档

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding.

Number:如果字母数为 1,则使用最小位数输出该值,并且不进行填充。

So the format specifier you want is M/d/yyyy, using single letter forms. Of course, it will still parse date Strings like "12/30/1969"correctly as for these day/month values, two digits are the “minimum number of digits”.

所以你想要的格式说明符是M/d/yyyy,使用单字母形式。当然,它仍然会String"12/30/1969"这些日/月值一样正确解析日期,两位数是“最小位数”。

The important difference is that MMand ddrequire zero padding, not that Mand dcan't handle values greater than 9 (that would be a bit… unusual).

最重要的区别是,MMdd需要补零,而不是Md不能处理的值大于9(这将是一个有点...不寻常的)。

回答by Joginder Malik

In Java 8 Date Time API, I recently used

在 Java 8 Date Time API 中,我最近使用了

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

System.out.println(LocalDate.parse("10/22/2020", formatter));
System.out.println(LocalDate.parse("2/21/2020", formatter));