Support for Instant type (#21)

Since `Instant` requires a timezone which is not stored/accessible from the database,
all `Instant` objects are instantiated with UTC timezone by default
This commit is contained in:
Francesco 2023-10-22 16:33:10 +02:00
parent e52cc2877f
commit d3f516edaf
2 changed files with 35 additions and 1 deletions

View File

@ -25,9 +25,11 @@ import java.math.BigInteger;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Locale;
@ -270,6 +272,28 @@ public enum DbFieldType {
return List.of(CompareOperator.AFTER, CompareOperator.STRING_EQ, CompareOperator.BEFORE);
}
},
INSTANT {
@Override
public String getFragmentName() {
return "datetime";
}
@Override
public Object parseValue(Object value) {
if (value == null || value.toString().isBlank()) return null;
return LocalDateTime.parse(value.toString()).toInstant(ZoneOffset.UTC);
}
@Override
public Class<?> getJavaClass() {
return Instant.class;
}
@Override
public List<CompareOperator> getCompareOperators() {
return List.of(CompareOperator.AFTER, CompareOperator.STRING_EQ, CompareOperator.BEFORE);
}
},
STRING {
@Override
public String getFragmentName() {
@ -626,6 +650,8 @@ public enum DbFieldType {
return DATE;
} else if (klass == LocalDateTime.class) {
return LOCAL_DATE_TIME;
} else if (klass == Instant.class) {
return INSTANT;
} else if (klass == Float.class || klass == float.class) {
return FLOAT;
} else if (klass == Double.class || klass == double.class) {

View File

@ -19,8 +19,10 @@
package tech.ailef.dbadmin.external.dbmapping;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnore;
@ -41,7 +43,7 @@ public class DbFieldValue {
public Object getValue() {
/*
* Special handling of OffsetDateTime to be compatbile
* Special handling of OffsetDateTime and Instant to be compatabile
* with the HTML datetime-local input field: we "cast"
* it to a LocalDateTime so the toString() method will
* not produce the ending "Z" which prevents the datepicker
@ -51,6 +53,12 @@ public class DbFieldValue {
return LocalDateTime.from((OffsetDateTime)value);
}
if (value instanceof Instant) {
Instant i = (Instant)value;
LocalDateTime result = LocalDateTime.ofInstant(i, ZoneId.of("UTC"));
return result;
}
return value;
}