In Java, you can convert a Date
to a Timestamp
by creating a Timestamp
object that represents the same time as the Date
. The Timestamp
class is a subclass of java.util.Date
and provides nanosecond precision, unlike the Date
class which only provides millisecond precision.
Here’s how you can do it:
Code Example:
import java.util.Date;
import java.sql.Timestamp;
public class DateToTimestamp {
public static void main(String[] args) {
// Create a Date object
Date date = new Date();
// Convert Date to Timestamp
Timestamp timestamp = new Timestamp(date.getTime());
// Print both Date and Timestamp
System.out.println("Date: " + date);
System.out.println("Timestamp: " + timestamp);
}
}
Explanation:
new Date()
creates aDate
object representing the current time.date.getTime()
gets the time in milliseconds (from the Unix epoch) from theDate
object.new Timestamp(long time)
creates aTimestamp
object using the milliseconds returned bygetTime()
.
Output:
If you run the code, the output will look something like this (depending on the current date and time):
Date: Sun Jan 20 15:30:45 GMT 2025
Timestamp: 2025-01-20 15:30:45.123
The Timestamp
has nanosecond precision (though you may not see the nanoseconds if they are zero in this case).