我无法使用 LocalDate 解析方法解析此示例日期字符串 - “312015”代表“2015 年 1 月 3 日”。 有人可以帮忙吗?
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class TestDOB {
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
String dateOfBirth = "312015";
SimpleDateFormat sdf = new SimpleDateFormat("dMyyyy");
System.out.println(sdf.parse(dateOfBirth));
// The above outputs Sat Jan 03 00:00:00 CST 2015
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dMyyyy").withLocale(Locale.getDefault());
LocalDate dateTime = LocalDate.parse(dateOfBirth, dateFormatter);
// The above parsing statement with LocalDate parse method runs into below error -
}
}
Error on console-
Exception in thread "main" java.time.format.DateTimeParseException: Text '312015' could not be parsed at index 6
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)
at TestDOB.main(TestDOB.java:30)
最佳答案
DateTimeFormatterBuilder.appendValue(TemporalField, int)
我很惊讶地发现这是可能的(这对我来说没有多大意义)。
DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.DAY_OF_MONTH, 1)
.appendValue(ChronoField.MONTH_OF_YEAR, 1)
.appendValue(ChronoField.YEAR, 4)
.toFormatter();
String dateOfBirth = "312015";
LocalDate dateTime = LocalDate.parse(dateOfBirth, dateFormatter);
System.out.println(dateTime);
此代码段的输出是:
2015-01-03
不过,它有一些我认为非常严重的限制:它只能解析 1 月到 9 月(不是 10 月到 12 月)中每月 1-9 天(而不是 10-31)内的日期,因为它坚持每月的日期和月份各只有 1 位数字。
您可以通过在第一次调用 appendValue() 时省略第二个参数
.类似的技巧对于本月不起作用,因此一年的最后一个季度是遥不可及的。1
来摆脱某月某日的限制
为什么单 d 和单 M 不起作用?
Why enforcing single d and single M doesn't work here? Am I missing something here?
对于DateTimeFormatter
,数字字段的一个模式字母被视为“尽可能多的数字”(而不是预期的“1 位数字”)。它没有很好的记录。文档中有这句话的提示:
If the count of letters is one, then the value is output using the minimum number of digits and without padding.
所发生的情况是,解析会处理一个月中的某一天尽可能多的数字(内部限制为 19)。在本例中是整个字符串。现在它无法解析任何月份。这是错误消息的原因:
Text '312015' could not be parsed at index 6
索引 6 是字符串的结尾。
文档链接
关于java - DateTimeFormatter 无法解析日期字符串,但 SimpleDateFormat 可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59619669/