In Java, dates are typically represented by java.util.Date
, which, despite its design flaws, serves as the foundation for managing date and time. It relies on Epoch time, stored as a long (timestamp), and includes both date and time information, with millisecond precision.
On the SQL side, standard date and time types include DATE, TIME, and TIMESTAMP (often referred to as DATETIME in some databases). In JDBC, these correspond to java.sql.Date
, java.sql.Time
, and java.sql.Timestamp
, all of which are subclasses of java.util.Date
. The precision of these types varies by database, typically aligning with Java’s millisecond precision but sometimes using seconds instead.
Unlike java.util.Date
, java.sql.Date
only stores date information (year, month, day), while java.sql.Time
holds only time information (hours, minutes, seconds). java.sql.Timestamp
, however, contains both date and time information, similar to java.util.Date
.
To store a timestamp in the database (using java.util.Date
in Java and java.sql.Timestamp
in JDBC), the common practice is to utilize PreparedStatement#setTimestamp()
:
java.util.Date date = new java.util.Date();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);
To retrieve a timestamp from the database, you would typically use ResultSet#getTimestamp()
:
Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can simply upcast.
more in Mysql documentation