因此,当尝试使用 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 Jul 03 00:00:00 BST 2016
getDate("3/7/2016T00:00:00.0+0100"); // Sun Jul 03 00:00:00 BST 2016
getLocalDate("03/07/2016"); // 2016-07-03
getLocalDate("3/7/2016"); // null
getLocalDate("3/7/2016 00:00:00"); // null
getLocalDate("3/7/2016 00:00:00.0+0100"); // null
getLocalDate("3/7/2016T00:00:00.0+0100"); // null
}
正如您所看到的,当两个格式化程序中使用相同的模式时,DateTimeFormatter 最终会生成空值,您希望看到的日期与 SDF 的日期相同。在这种情况下,我希望删除不需要的数据,但事实并非如此。
那么,我们如何创建一个强大的日期/时间解析器?!
因此,可能还有其他答案,但我提出的答案适合我遇到的最极端的情况。首先,我将 dd/MM 减少为 d/M。这表示预期字符的最小数量,因此可以完全解析两位数。请注意,您还可以使用 new DateTimeFormatterBuilder().parseLenient() 但这似乎没有必要。
其次,我决定在格式模式本身中使用可选子句。这允许您指定可能不提供哪些部分,这正是我试图解决的情况。
留给我们:
DateTimeFormatter.ofPattern("d/M/yyyy[' ']['T'][H:mm[:ss[.S]]][X]");
现在将处理提供带或不带时间的日期,包括 T 分隔符、秒、毫秒和区域偏移量。
运气好的话,这可以帮助别人!
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy[' ']['T'][H:mm[:ss[.S]]][X]");
public LocalDate getRobustLocalDate(String value) {
try {
return LocalDate.parse(value, formatter);
} catch (DateTimeParseException e) {
return null;
}
}
@Test
public void testDates() {
getRobustLocalDate("03/07/2016"); // 2016-07-03
getRobustLocalDate("3/7/2016"); // 2016-07-03
getRobustLocalDate("3/7/2016 00:00:00"); // 2016-07-03
getRobustLocalDate("3/7/2016 00:00:00.0+0100"); // 2016-07-03
getRobustLocalDate("3/7/2016T00:00:00.0+0100"); // 2016-07-03
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)