tl;dr
myPreparedStatement.setObject(
… ,
ZonedDateTime.of( 2016 , 5 , 23 , 15 , 57 , 22 , 0 , ZoneId.of( "Africa/Casablanca" ) )
) ;
Details
Using java.time classes with a driver supporting JDBC 4.2 or later for a MySQL 5.7 TIMESTAMP
column…
Time zone
Determine your time zone intended for that date-time. A date-time has no exact meaning without a time zone. For example, noon in Paris France arrives much earlier than noon in Montréal Québec.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime
& Instant
Use your inputs along with the time zone to instantiate a ZonedDateTime
to represent a moment on the timeline.
ZonedDateTime zdt = ZonedDateTime.of( 2016 , 5 , 23 , 15 , 57 , 22 , 0 , z ) ;
Extract the same moment as a value in UTC.
Instant instant = zdt.toInstant() ;
Send to the database.
myPreparedStatement.setObject( … , instant ) ;
And retrieve.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
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.
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.