【发布时间】:2020-04-24 10:38:40
【问题描述】:
我无法使用 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)
【问题讨论】:
-
你怎么能期望“31”被(可靠地)检测为“3rd Jan”,而不是“31st”?
d将匹配多个数字,因为有时它必须这样做。 -
即使你强制
d和M只匹配一个数字,那么1122019呢?是1/12/2019还是11/2/2019?不要使用允许以相同方式表示两个单独日期的格式。 -
我有一个特殊要求来解析没有特殊字符或空格并且严格只包含数字的日期字符串
-
为什么强制单 d 和单 M 在这里不起作用?我在这里错过了什么吗?
-
即使它们只能是数字,为什么不使用两位数来表示日和月呢?
标签: java datetime-format localdate