[英]DateTimeFormatter unable to parse a Date String but SimpleDateFormat is able to
我无法使用 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)
我很惊讶地发现这是可能的(这对我来说没有多大意义)。
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 在这里不起作用? 我在这里错过了什么吗?
对于DateTimeFormatter
,数字字段的一个模式字母表示“尽可能多的数字”(而不是预期的“1 位数字”)。 它没有很好的记录。 文档中有这句话的提示:
如果字母数为 1,则使用最小位数输出该值并且不进行填充。
发生的情况是,解析会在一个月中的某一天(最多 19 位内部限制)消耗尽可能多的数字。 在这种情况下,整个字符串。 现在它无法解析任何月份。 这是错误消息的原因:
无法在索引 6 处解析文本“312015”
索引 6 是字符串的结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.