【发布时间】:2018-09-20 10:37:46
【问题描述】:
如果字符串包含有效的日期输入,我需要验证它们。为此我创建了一个方法
public static Date validateDateFormat(final String expectedDateFormat, final String dateToValdate) {
DateTimeFormatter formatter = DateTimeFormat.forPattern(expectedDateFormat);
DateTime dt = null;
try {
dt = formatter.parseDateTime(dateToValdate);
} catch (Exception e) {
log.error("cannot parse {0} to format {1}", dateToValdate, expectedDateFormat);
}
if (dt != null) {
return dt.toDate();
}
else {
return null;
}
}
使用这些值,它不会按预期返回 null。该字符串将转换为值为 0018-12-18T00:00:00.000+00:53:28 的 DateTime,有没有办法改变这种行为?我认为如果格式不正确,它会失败。
这是我的测试
@Test
public void checkFormat6() {
String date = "18.12.18";
String expectedFormat = "dd.MM.yyyy";
assertNull(DateFormatChecker.validateDateFormat(expectedFormat, date));
}
我需要使用 JDK 7 并使用 joda-time 2.10
【问题讨论】:
-
范围检查?您知道您将接受的日期范围,并且由于它不会追溯到 18 年,因此请拒绝任何日期。