LocalDateTime , ZonedDateTime and Timestamp

痞子三分冷 提交于 2019-11-30 04:05:21

Timestamp extends Date to provide nanosecond accuracy. Neither Date nor Timestamp are designed to refer to a specific timezone as ZoneDateTime.

If you need to convert ZonedDateTime -> Timestamp you will have to discard the timezone/offset information. E.g.

LocalDateTime withoutTimezone = zoneDateTime.toLocalDateTime();
Timestamp timestamp = Timestamp.valueOf(withoutTimezone));

and for converting Timestamp -> ZonedDateTime you need to specify an offset:

LocalDateTime withoutTimezone = sqlTimestamp.toLocalDateTime();
ZonedDateTime withTimezone = withoutTimezone.atZone(ZoneId.of("+03:00"));

or timezone:

ZonedDateTime withTimezone = withoutTimezone.atZone(ZoneId.of("Europe/Paris"));

If your intention is to save ZonedDateTime variables in the database and preserve the various timezones specified there, I recommend designing your database accordingly. Suggestions:

  1. Use a column of type DATETIME to save a LocalDateTime and a VARCHAR saving a timezone like "Europe/Paris" or a SMALLINT saving an offset in minutes.
  2. Convert the ZonedDateTime to a String and save in a VARCHAR column like "2017-05-16T14:12:48.983682+01:00[Europe/London]". You'll then have to parse it when reading from the database.

Jon Skeet said it already:

@Override
public Timestamp convertToDatabaseColumn(ZonedDateTime zoneDateTime) {
    return zoneDateTime == null ? null : Timestamp.from(zoneDateTime.toInstant());
}

@Override
public ZonedDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
    return sqlTimestamp == null ? null : sqlTimestamp.toInstant().atZone(ZoneId.systemDefault());
}

Jon also asked the good question, which time zone do you want? I have guessed at ZoneId.systemDefault(). Obviously a different time zone will give a different result, so I hope you will think twice and will be able to find the right time zone for your purpose.

PS I have reduced the usage of parentheses since I found it more readable with fewer. You can add them back in if you prefer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!