仅出于完整性考虑,以下是lambda和方法参考的解决方案:
ISO格式?
说明:以下方法
- 将
String
带有模式的yyyy-MM-dd
a转换为Timestamp
如果输入的值有效,则将为,
null
如果null
给出值,则返回,
DateTimeParseException
如果给出了无效的输入,则抛出一个
代码:
static Timestamp convertStringToTimestamp(String strDate) {
return Optional.ofNullable(strDate)
.map(str -> LocalDate.parse(str).atStartOfDay())
.map(Timestamp::valueOf)
.orElse(null);
}
验证:可以使用以下单元测试来测试此方法:(使用Junit5和Hamcrest)
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
String strDate = "2020-01-30";
final Timestamp result = convertStringToTimestamp(strDate);
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenInvalidInput() {
String strDate = "7770-91-30";
assertThrows(DateTimeParseException.class, () -> convertStringToTimestamp(strDate));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenNullInput() {
final Timestamp result = convertStringToTimestamp(null);
assertThat(result, is(nullValue()));
}
另一种格式?
通常,要解析的字符串带有另一种格式。处理它的一种方法是使用格式化程序将其转换为另一种格式。这是一个例子:
输入: 20200130 11:30
模式: yyyyMMdd HH:mm
输出:此输入的时间戳
代码:
static Timestamp convertStringToTimestamp(String strDate) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
return Optional.ofNullable(strDate)
.map(str -> LocalDateTime.parse(str, formatter))
.map(Timestamp::valueOf)
.orElse(null);
}
测试:
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
String strDate = "20200130 11:30";
final Timestamp result = convertStringToTimestamp(strDate);
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
assertThat(dateTime.getHour(), is(11));
assertThat(dateTime.getMinute(), is(30));
}