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 field 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

  1. Obtain a java.sql.Timestamp object representing the timestamp value you want to convert.
  2. 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.
  3. 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.
import java.sql.Timestamp; import java.util.Date; public class TimestampToDateExample { public static void main(String[] args) { // Create a Timestamp object Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // Convert Timestamp to Date Date date = new Date(timestamp.getTime()); // Print the converted Date System.out.println("Timestamp: " + timestamp); System.out.println("Date: " + date); } }

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:

import java.sql.Timestamp; import java.util.Date; public class TimestampToDateExample { public static void main(String[] args) { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); Date date = timestamp.toDate(); System.out.println(date); // Prints the date in the default format } }
Keep in mind when converting a Timestamp to a Date:
  1. 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.
  2. 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.
  3. 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.