Signup/Sign In

How to convert Java TimeStamp to Date

In Java, TimeStamp can be converted into Date using the constructor of the Date class of the java.util package.

It must be noted that Date class takes an argument as a long value hence the TimeStamp object needs to be converted into long. This is done using the getTime() method of Timestamp class of the java.sql package.

Example 1:

Here, the TimeStamp is converted into Date by using the Date constructor. See the example below.

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

public class StudyTonight
{    
	public static void main(String args[])
	{    
		Timestamp t = new Timestamp(System.currentTimeMillis()); //for current time in milliseconds 
		Date d = new Date(t.getTime());  
		System.out.println(d);                      
	}    
}


Thu Sep 24 05:28:11 UTC 2020

Example 2:

Also, the Timestamp class extends the Date class. Hence, the instance of the Timestamp class can directly be assigned into Date and the output like Timestamp can be obtained. But, it is undesirable because the milliseconds and nanoseconds can be lost in this case.

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

public class StudyTonight
{    
	public static void main(String args[])
	{    
		Timestamp t = new Timestamp(System.currentTimeMillis());  
		Date d = t;  
		System.out.println(d);                       
	}    
}


2020-09-24 05:48:58.627

Example 3:

Here, the TimeStamp is converted into Date with formatting into various formats.

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

public class StudyTonight
{    
	public static void main(String args[])
	{    
		Timestamp stamp = new Timestamp(System.currentTimeMillis());
		Date date = new Date(stamp.getTime());
		DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat f1 = new SimpleDateFormat("yyyy/MM/dd");
		String d = f.format(date);
		String d1 = f1.format(date);
		System.out.println(d);
		System.out.println(d1);
	}    
}  


2020-10-15
2020/10/15



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.