Java Date to Timestamp

To convert a java.util.Date to a java.sql.Timestamp in Java, you can simply pass the Date object to the constructor of Timestamp. Timestamp is a subclass of java.util.Date, so the conversion is straightforward. Here’s how you can do it:

1. Using the Timestamp Constructor

You can create a Timestamp object by passing the Date.getTime() (which returns the milliseconds since the Unix epoch) to the Timestamp constructor.


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

public class DateToTimestampExample {
    public static void main(String[] args) {
        // Create a Date object
        Date date = new Date();  // current date and time

        // Convert Date to Timestamp
        Timestamp timestamp = new Timestamp(date.getTime());

        // Print the result
        System.out.println("Date: " + date);
        System.out.println("Timestamp: " + timestamp);
    }
}

Explanation:

1. date.getTime() returns the time in milliseconds since the Unix epoch (January 1, 1970, 00:00:00 GMT).

2. Timestamp has a constructor that takes a long value representing the time in milliseconds.

2. Using Date to Timestamp Conversion in SQL Context

When working with JDBC, Timestamp is often used to represent date and time data in databases. If you’re dealing with database operations, you can directly convert a java.util.Date to a java.sql.Timestamp using the same approach.

Example with JDBC (Optional):


import java.sql.*;
import java.util.Date;

public class DateToTimestampJDBC {
    public static void main(String[] args) throws SQLException {
        // Create a Date object
        Date date = new Date();

        // Convert Date to Timestamp
        Timestamp timestamp = new Timestamp(date.getTime());

        // Example JDBC usage (assuming a connection 'conn' exists)
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase", "username", "password");
        
        // Example of using the Timestamp with a PreparedStatement
        String query = "INSERT INTO your_table (your_timestamp_column) VALUES (?)";
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setTimestamp(1, timestamp);
        pstmt.executeUpdate();
        
        // Close resources
        pstmt.close();
        conn.close();

        // Print the result
        System.out.println("Timestamp: " + timestamp);
    }
}

3. Using Timestamp directly (if you already have a Timestamp)

If the object is already a Timestamp and you want to ensure you have it in Timestamp form, no conversion is necessary, because Timestamp is a subclass of Date:


import java.sql.Timestamp;

public class DirectTimestampExample {
    public static void main(String[] args) {
        // Create a Timestamp object directly
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        // Print the result
        System.out.println("Timestamp: " + timestamp);
    }
}