Convert Timestamp to Date | Java
The java.sql.Timestamp class serves as a refined layer atop java.util.Date that facilitates recognition by the JDBC API as an SQL TIMESTAMP value. It offers an enhanced capability to accommodate the precision of nanoseconds, enabling the storage of fractional seconds for SQL TIMESTAMP. In the realm of JDBC, we are familiar with three types: JDBC DATE, JDBC TIME, and JDBC TIMESTAMP, which pertain to date and time representations.
There are two ways to convert a Timestamp to a Date in Java:
Using the getTime() method
- Obtain a java.sql.Timestamp object representing the timestamp value you want to convert.
- Create a java.util.Date object and initialize it using the timestamp's getTime() method, which returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.
- If necessary, you can format the date using a java.text.DateFormat instance or a java.time.format.DateTimeFormatter to represent it in a specific format.
In the above code, we create a Timestamp object using the current system time (System.currentTimeMillis()). Then, we create a Date object by passing the timestamp's time in milliseconds (timestamp.getTime()). Finally, we print both the original timestamp and the converted date.
Using the toDate() method
The toDate() method of the Timestamp class returns a Date object that represents the same date and time as the Timestamp object. The following code shows how to do this:
- The getTime() method and the toDate() method return the same date and time, but the getTime() method returns the date and time as a long value, while the toDate() method returns a Date object.
- The getTime() method and the toDate() method can be used with any Timestamp object, regardless of whether it was created using the Timestamp class constructor or the new Timestamp() expression.
- The getTime() method and the toDate() method can be used with any Date object, regardless of whether it was created using the Date class constructor or the new Date() expression.