Java Program to Convert Date to TimeStamp
Last Updated :
22 Oct, 2021
We can convert date to timestamp using the Timestamp class which is present in the SQL package.
- The constructor of the time-stamp class requires a long value.
- So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).
Example:
Input: Date is 19 October 2021
Output: 2021-10-19 18:11:24
Explanation: Date would be printed along with the current time to milliseconds.
TimeStamp Class
The TimeStamp class presents formatting and parsing methods to support JDBC escape syntax. It also combines the ability to hold the SQL TIMESTAMP fractional seconds value.
How to use TimeStamp Class?
- Import the java.sql.Timestamp package.
- Import the java.util.Date package
- Create an object of the Date class.
- Convert it to long using getTime() method
Syntax:
public long getTime()
Parameters: The function does not accept any parameter.
Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM.
- Create an object of the Timestamp class and pass the value returned by the getTime() method.
- Finally, print this Timestamp object value.
Example:
Java
import java.sql.Timestamp;
import java.util.Date;
public class GFG_Article {
public static void main(String args[])
{
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
System.out.println(ts);
}
}
|
Output
2021-10-19 20:18:08.813
Formatting the TimeStamp Value:
- We can format the Timestamp value using SimpleDateFormat class.
- Initially, by using the Timestamp class, the time is getting displayed in a standard format, but we can format it to our own choice using SimpleDateFormat class.
Example:
Java
import java.sql.Timestamp;
import java.util.Date;
import java.text.SimpleDateFormat;
public class GFG {
public static void main(String args[])
{
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
SimpleDateFormat formatter
= new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
System.out.println(formatter.format(ts));
SimpleDateFormat formatter1
= new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
System.out.println(formatter1.format(ts));
}
}
|
Output
2021-10-19 20:21:34
2021-10-19 20:21
Share your thoughts in the comments
Please Login to comment...