因此,当尝试使用SimpleDateFormat和Date替换一些遗留代码时,要使用java.time.DateTimeFormatter和LocalDate,我遇到了一个问题.两种日期格式不相同.在这一点上,我必须说我知道两种日期类型不一样,但我所处的场景意味着我从不关心时间方面,所以可以忽略它.
public Date getDate(String value) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
return dateFormat.parse(value);
} catch (ParseException e) {
return null;
}
}
public LocalDate getLocalDate(String value) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try {
return LocalDate.parse(value, formatter);
} catch (DateTimeParseException e) {
return null;
}
}
public void testDates() {
getDate("03/07/2016"); // Sun Jul 03 00:00:00 BST 2016
getDate("3/7/2016"); // Sun Jul 03 00:00:00 BST 2016
getDate("3/7/2016 00:00:00"); // Sun Jul 03 00:00:00 BST 2016
getDate("3/7/2016 00:00:00.0+0100"); // Sun …Run Code Online (Sandbox Code Playgroud)