Timestamp has higher precision as it includes fraction seconds, while a Date is accurate upto seconds as it doesn’t include fraction of seconds. In this guide, we will see java programs to convert a given Date to Timestamp.
Program to Convert Date to Timestamp
Timestamp constructor expects a long argument, it constructs a Timestamp object using the provided milliseconds value. This value must be a long data type.
Timestamp ts = new Timestamp(long time)
To pass the time value as a long data type, we can use the getTime()
method of Date class.
public long getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
Let’s write a program using this information:
import java.sql.Timestamp; import java.util.Date; public class JavaExample { public static void main(String args[]){ Date date = new Date(); //get current date Timestamp ts = new Timestamp(date.getTime()); System.out.println("Date is: "+date); System.out.println("Timestamp is: "+ts); } }
Output:
As you can see that the Date and Timestamp values are same except that Timestamp has precision upto fraction seconds. The format of Date and Timestamp is also different, however you can change it using SimpleDateFormat as shown below:
import java.sql.Timestamp; import java.util.Date; import java.text.SimpleDateFormat; public class JavaExample { public static void main(String args[]){ Date date = new Date(); Timestamp ts = new Timestamp(date.getTime()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(sdf.format(ts)); //Day Name SimpleDateFormat sdf2 = new SimpleDateFormat("EEE MMM YY hh:mm:ss"); System.out.println(sdf2.format(ts)); //include AM and PM SimpleDateFormat sdf3 = new SimpleDateFormat("EEE HH:mm:ss aa"); System.out.println(sdf3.format(ts)); } }
Output:
References: Date and Timestamp documentation