只是为了完整起见,这里有一个带有 lambda 和方法参考的解决方案:
ISO格式?
描述:以下方法
String
如果给出有效输入,则将带有模式的 a转换yyyy-MM-dd
为 a Timestamp
,
- 返回 a
null
,如果null
给定了一个值,
DateTimeParseException
如果给出了无效的输入,则抛出一个
代码:
static Timestamp convertStringToTimestamp(String strDate) {
return Optional.ofNullable(strDate) // wrap the String into an Optional
.map(str -> LocalDate.parse(str).atStartOfDay()) // convert into a LocalDate and fix the hour:minute:sec to 00:00:00
.map(Timestamp::valueOf) // convert to Timestamp
.orElse(null); // if no value is present, return null
}
验证:可以使用这些单元测试来测试此方法:(使用Junit5和Hamcrest)
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "2020-01-30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
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() {
// given
String strDate = "7770-91-30";
// when, then
assertThrows(DateTimeParseException.class, () -> convertStringToTimestamp(strDate));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenNullInput() {
// when
final Timestamp result = convertStringToTimestamp(null);
// then
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() {
// given
String strDate = "20200130 11:30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
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));
}