To convert a java.sql.Timestamp to a java.util.Date in Java, you can use the getTime() method from the Timestamp object, which returns the milliseconds since the Unix epoch. You can then pass this long value to the Date constructor.
1. Using getTime() and Date Constructor
You can convert a Timestamp to a Date by passing the time value (getTime()) from Timestamp to the Date constructor.
import java.sql.Timestamp;
import java.util.Date;
public class TimestampToDateExample {
public static void main(String[] args) {
// Create a Timestamp object (current timestamp)
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// Convert Timestamp to Date
Date date = new Date(timestamp.getTime());
// Print the results
System.out.println("Timestamp: " + timestamp);
System.out.println("Date: " + date);
}
}
Explanation:
- timestamp.getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 UTC (Unix epoch), which is a long value.
- new Date(long millis) creates a new Date object with the given time in milliseconds.
2. Using Timestamp directly as a Date
Since Timestamp is a subclass of java.util.Date, you can simply assign a Timestamp object to a Date reference because Timestamp inherits from Date. However, keep in mind that this doesn’t change the type, but it allows you to treat the Timestamp as a Date object.
import java.sql.Timestamp;
import java.util.Date;
public class TimestampToDateExample {
public static void main(String[] args) {
// Create a Timestamp object (current timestamp)
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// Use Timestamp as a Date object
Date date = timestamp;
// Print the results
System.out.println("Timestamp: " + timestamp);
System.out.println("Date: " + date);
}
}
Explanation: Since Timestamp extends java.util.Date, you can assign a Timestamp object to a Date reference directly.