tl;dr
Both of the troublesome Date
& Timestamp
classes are now replaced by java.time.Instant
.
Instant.now()
.toString()
2018-04-04T21:33:37.889228Z
java.time
The Answer by Vidya and by rgettman are both correct, you have run into the limits designed in those classes.
Also, those classes are troublesome, confusing, and flawed. They have been supplanted by the java.time classes. No need to ever use java.util.Date
or java.sql.Timestamp
again.
The java.util.Date
class represents a moment on the timeline in UTC with resolution of milliseconds. That class is now replaced by java.time.Instant
, also a moment in UTC, but with a finer resolution of nanoseconds.
Instant instant = Instant.now() ;
In Java 8 specifically, capturing the current moment is limited to milliseconds despite the Instant
class being capable of holding nanoseconds. In Java 9 and later, a fresh implementation of Clock
allows for capturing the current moment in finer resolution, though limited by the capability of your host OS & hardware. In Oracle JDK 9.0.4 on macOS Sierra, I am seeing microseconds
Instant.now().toString(): 2018-04-04T21:33:37.889228Z
The java.sql.Timestamp
class is also replaced by Instant
as of JDBC 4.2 and later. You can now directly exchange java.time classes, and forget about the java.sql types.
myPreparedStatement.setObject( … , instant ) ;
…and…
Instant instant = myResultSet.getObject( … , Instant.class ) ;
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.