Open In App

Java Program to Convert Date to TimeStamp

We can convert date to timestamp using the Timestamp class which is present in the SQL 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?



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.

Example:




// Java Program to convert date to time stamp
  
import java.sql.Timestamp;
import java.util.Date;
public class GFG_Article {
    public static void main(String args[])
    {
        
        // getting the system date
        Date date = new Date();
        
        // getting the object of the Timestamp class
        Timestamp ts = new Timestamp(date.getTime());
        
        // printing the timestamp of the current date
        System.out.println(ts);
    }
}

Output
2021-10-19 20:18:08.813

Formatting the TimeStamp Value:

Example:




// Java program to convert date to time-stamp using
// SimpleDataFormat class and TimeStamp class
  
import java.sql.Timestamp;
import java.util.Date;
import java.text.SimpleDateFormat;
  
public class GFG {
    
    public static void main(String args[])
    {
        
        // getting the system date
        Date date = new Date();
        
        // getting the timestamp object
        Timestamp ts = new Timestamp(date.getTime());
        
        // using SimpleDateFormat class,we can format the
        // time-stamp according to ourselves
        // getting the timestamp upto sec
        SimpleDateFormat formatter
            = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
       System.out.println(formatter.format(ts));
        
       // getting the timestamp to seconds
       SimpleDateFormat formatter1
            = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        
      // printing the timestamp
      System.out.println(formatter1.format(ts));
          
    }
}

Output
2021-10-19 20:21:34
2021-10-19 20:21

Article Tags :