Skip to content

Commit

Permalink
fix: 修复无法解析java.sql.Date问题
Browse files Browse the repository at this point in the history
  • Loading branch information
zhou-hao committed Sep 24, 2024
1 parent fee0f73 commit 3cb38e5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ public class DateTimeCodec implements ValueCodec {

private String format;

private Class toType;
private Class<?> toType;

public DateTimeCodec(String format, Class toType) {
public DateTimeCodec(String format, Class<?> toType) {
this.format = format;
this.toType = toType;
}
Expand All @@ -48,10 +48,11 @@ public Object encode(Object value) {
}
if (value instanceof String) {
if (((String) value).contains(",")) {
return Arrays.stream(((String) value).split(","))
.map(this::doParse)
.filter(Objects::nonNull)
.collect(Collectors.toList());
return Arrays
.stream(((String) value).split(","))
.map(this::doParse)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}

return doParse(((String) value));
Expand All @@ -68,6 +69,10 @@ public Object decode(Object data) {
if (toType.isAssignableFrom(data.getClass())) {
return data;
}
// java.sql.Date 无法使用toInstant
if (data instanceof java.sql.Date) {
data = new Date(((java.sql.Date) data).getTime());
}
if (!(data instanceof Date)) {
data = toDate(data);
}
Expand Down Expand Up @@ -118,7 +123,7 @@ public Object toDate(Object data) {
} else if (data instanceof ZonedDateTime) {
ZonedDateTime dateTime = ((ZonedDateTime) data);
data = Date.from(dateTime.toInstant());
}else if(data instanceof OffsetDateTime){
} else if (data instanceof OffsetDateTime) {
data = Date.from(((OffsetDateTime) data).toInstant());
} else if (data instanceof String) {
String stringData = ((String) data);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,19 @@ public void testDecodeStringTime() {
assertEquals(Lists.newArrayList(now, now), decode);
}
}

@Test
public void testDecodeSqlDate() {
DateTimeCodec codec = new DateTimeCodec("yyyy-MM-dd", LocalDateTime.class);

java.sql.Date data = new java.sql.Date(System.currentTimeMillis());

Object val = codec.encode(data);
assertEquals(data, val);

Object date = codec.encode("2019-01-01");

assertTrue(codec.decode(date) instanceof LocalDateTime);
}

}

0 comments on commit 3cb38e5

Please sign in to comment.