Signup/Sign In
LAST UPDATED: DECEMBER 1, 2020

How to convert Java Date to TimeStamp

In Java, Date can be converted into TimeStamp by using the constructor of the TimeStamp class which is the part of the java.sql package.

It must be noted that the constructor of the TimeStamp class takes Date as a long value as the argument, hence the date must be converted into long using the getTime() method which is the part of Date class of the java.util package.

Example 1:

Here, the Date is converted into TimeStamp.

import java.sql.Timestamp;
import java.util.Date;  

public class CoreJava
{    
	public static void main(String args[])
	{    
		Date d = new Date();  //object of Date class
		Timestamp t = new Timestamp(d.getTime());  
		System.out.println(t);                     
	}    
}  


2020-09-24 04:41:32.471

Example 2:

Here, the TimeStamp value is formatted in yyyy-MM-dd HH:mm: ss format using the constructor of SimpleDateFormat class of java.text package.

import java.sql.Timestamp;    
import java.util.Date; 
import java.text.SimpleDateFormat;

 public class StudyTonight
 {    
   public static void main(String args[])
    {    
      Date d = new Date();  
      Timestamp t = new Timestamp(d.getTime());  
      SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
      System.out.println(f.format(t));                        
    }    
}  


2020-09-24 04:49:06

Example 3:

Here, the String Date is converted into TimeStamp using the valueOf() method of the Timestamp class.

import java.sql.Timestamp;    
import java.util.Date; 
import java.text.SimpleDateFormat;

public class CoreJava
{    
	public static void main(String args[])
	{    
		String input = "2007-11-11 12:13:14" ;
		Timestamp ts = Timestamp.valueOf( input ) ; 
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd ");  
		System.out.println(f.format(ts));
	}    
}  


2007-11-11



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.