How to Convert Date to Timestamp in Java
How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can pass to java.sql.Timestamp. It creates a new instance of the Timestamp object in JDBC. The only way to create a Timestamp instance is to create the constructor of Timestamp class. It accepts a long value as an argument. So you need to convert date into long value using getTime() method of Date class. You can also format the output by using java.text.SimpleDateFormat class. Remember: Timestamp class is a wrapper around Date class to allow JDBC to view it as SQL Timestamp value. The signature of getTime() method of date class is: public long getTime() Example In the following example, we have import two packages namely java.sql.Timestamp and java.util.Date. We have created an object of Date class. Timestamp is a subclass of Date class. We have created a constructor of Timestamp class and passes time as an argument. It returns the current date and time. The println statement prints the data and time.
import java.sql.Timestamp; import java.util.Date; public class DateToTimestampExample { public static void main(String args[]) { Date date = new Date(); Timestamp tstamp=new Timestamp(date.getTime()); System.out.println(tstamp); } }Output
2019-05-29 11:05:02.166