DateTimeFormatter支持单个数月的月和月 [英] DateTimeFormatter Support for Single Digit Day of Month and Month of Year
问题描述
DateTimeFormmater
似乎不处理一个月的单位数字:
DateTimeFormmater
doesn't seem to handle single digit day of the month:
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)));
在此示例中, SimpleDateFormat
正确解析日期,但 DateTimeFormatter
抛出异常。如果我使用零填充日期,例如05/03/1969,都可以使用。但是,如果一个月中的一个月或一个月份是单位数,那么 DateTimeFormatter
会引发异常。
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.
什么是正确的 DateTimeFormatter
格式解析一个月和一个月的一个和两个数字的一天?
What is the right DateTimeFormatter
format to parse both one and two digit day of month and month of year?
推荐答案
从文档:
数字:如果字母数为1,则使用最小数字输出该值的数字和无填充。
Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding.
所以你想要的格式说明符是 M / d / yyyy
单字母形式。当然,它仍然解析日期 String
像12/30/1969
正确地像这些日子/月份值,两位数字是最小位数。
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".
重要的区别是 MM
和 dd
需要零填充,而不是 M
和 d
t处理大于9的值(这将有点...不寻常)。
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).
这篇关于DateTimeFormatter支持单个数月的月和月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!