Good day,
I create web application service, which would be used across the world.
Therefore I need to store datetime values in UTC and represent them in clocks on the wall time to the end user.
After reading Stack overflow, I understood, that I should:
- use timestamp as a column type in DB (currently MariaDB 10.1.20)
- use ZonedDateTime in Java (I use java8)
The problem arose while converting between these values.
As I use JDBC, I have to do the following conversion:
java.sql.Timestamp <-> java.time.ZonedDateTime
My code:
// Get current zonedDateTime
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
// Convert zonedDateTime to java.sql.Timestamp before saving to DB
Timestamp = Timestamp.from(zonedDateTime.toInstant());
// Get zonedDateTime from resultSet
Timestamp timestamp = (Timestamp) resultSet.getObject("created");
ZonedDateTime zonedDateTime =
ZonedDateTime.ofInstant(ts.toInstant(), ZoneOffset.UTC))
When I use:
zonedDateTimeBeforeSave.isEqual(zonedDateTimeAfterSave);
It returns me false (I need to compare them in overridden equal method of my domain model)
Below is print out of both:
zonedDateTimeBeforeSave: 2017-01-24T20:18:17.720Z
zonedDateTimeAfterSave: 2017-01-24T20:18:17Z
Questions:
- Am I right in my choice. Perhaps, I should use another column or java type...
- Am I right in doing conversions. Maybe there is another better way
Thank you
- Edit: After Matt Johnson's help I understood that the problem is in the fact, that when I save datetime to DB, It doesn't save fractions, though It should. FYI column type is timestamp(6).
- Edit: Now I use java.time.Instant instead of ZonedDateTime