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
DateTimeFormatter Support for Single Digit Day of Month and Month of Year
提问by Mark Maxey
DateTimeFormmater
doesn'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, SimpleDateFormat
correctly parses the date, but DateTimeFormatter
throws 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 DateTimeFormatter
throws an exception.
在本例中,SimpleDateFormat
正确解析日期,但DateTimeFormatter
抛出异常。如果我要使用零填充日期,例如“05/03/1969”,两者都有效。但是,如果月份中的某一天或年份中的月份是个位数,则DateTimeFormatter
抛出异常。
What is the right DateTimeFormatter
format 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 String
s 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 MM
and dd
require zero padding, not that M
and d
can't handle values greater than 9 (that would be a bit… unusual).
最重要的区别是,MM
和dd
需要补零,而不是M
和d
不能处理的值大于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));