Time zone matters
to avoid timezone issues in my project
You cannot ignore time zone issues. Wishful dreaming. Be brave, grab the bull by the horns, and take on the challenge of learning to deal with time zones. Your programming work will be much easier.
In your call to toDateTimeAtStartOfDay
, you chose to omit the argument for time zone, the DateTimeZone
object. So, at runtime, the JVM’s current default time zone was silently implicitly applied.
Then you convert to a java.sql.Timestamp (apparently – you were not explicit about package) which is always in UTC.
You did not provide your runtime current default time zone, so I cannot be more exact in the details.
Using java.time
The Joda-Time project is now in maintenance mode, with its team advising migration to the java.time classes. Both projects were led by the same man, Stephen Colebourne, so the they share the same conceptual approach. Pretty easy to switch over.
To get today’s date, specify the time zone. For any given moment, the date varies around the globe by zone.
See how we pass the zone to atStartOfDay
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z );
LocalDate twoDaysLater = today.plusDays( 2 ) ;
ZonedDateTime zdt = twoDaysLater.atStartOfDay( z ) ;
Instant instant = zdt.toInstant(); // Instant is always in UTC by definition.
With JDBC 4.2 and later, you can work directly with the java.time types. Call PreparedStatement.setObject
and ResultSet.getObject
.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.