I have a POST API like so:
@JsonDeserialize(using = MyCustomDeserializer.class)
@JsonSerialize(using = MyCustomSerializer.class)
@NotNull(message = "fromDate should not be blank!")
@FutureOrPresent(message = "fromDate must be of Future or Present")
private Instant fromDate;
I have custom serializer and deserializer like so in my utility package:
public class MyCustomSerializer extends JsonSerializer<Instant> {
private DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
@Override
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
String str = fmt.format(value);
gen.writeString(str);
}
}
public class MyCustomDeserializer extends JsonDeserializer<Instant> {
private DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
@Override
public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
LocalDate date = LocalDate.parse(p.getText());
return Instant.from(fmt.parse(date.toString()));
}
}
I want to save internally with time component as start of day. The API should be taking in and outputting by only date
I tried converting this to Instant
. Can someone assist how do I do this(store in db as date start_of_day) and expose/consume as yyyy-MM-dd?
CodePudding user response:
TL;DR:
return date.atStartOfDay(ZoneOffset.UTC).toInstant();
(Not tested, please forgive any typos.)
You are really trying to fit a square peg into a round whole. An Instant
is a point in time, and at that point in time it is two or three different dates in different time zones. Settling for UTC helps, then we can get it to work. It still isn’t ideal. The standard solution (hack) to the discrepancy is to represent the date as the start of the day in some time zone, and UTC is an excellent choice.
Why your code didn’t work: Parsing the date (after formatting it) in your deserializer gives the date and the UTC offset, but no time of day. We need all three to establish an unambiguous point in time. Instead in my code I explicitly specify the start of day.