I'm working on a Scala project and I need to map OffsetDateTime
type to SQL Timestamp
type. In DB I would like to have UTC times.
The conversion from OffsetDateTime
to Timestamp
is straightforward (hint from this question) and it works as expected:
import java.time._
import java.sql.Timestamp
val ofsdatetime = OffsetDateTime.now()
// ofsdatetime: java.time.OffsetDateTime = 2017-04-04T21:46:33.567+02:00
val tstamp = Timestamp.valueOf(ofsdatetime.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime())
// tstamp: java.sql.Timestamp = 2017-04-04 19:46:33.567
As you can see, timezone is removed and the Timestamp is two hours back in time (UTC), great!
Converting back Timestamp
to OffsetDateTime
isn't working as expected:
OffsetDateTime.ofInstant(Instant.ofEpochMilli(tstamp.getTime), ZoneId.systemDefault())
// java.time.OffsetDateTime = 2017-04-04T19:46:33.567+02:00
Timezone has been added to the newly created OffsetDateTime
, but the time is not correct (it's still UTC, I need that it is adapted to the actual timezone).
Why? What am I doing wrong?