Java Convert Date to Timestamp

Tags: Java Date Java Timestamp

In this Java core tutorial we learn how to convert a java.util.Date object to a java.sql.Timestamp object in Java programming language.

How to convert Date to Timestamp in Java

In Java program, with a given Date object we can follow these steps to convert it to Timestamp object.

  • Using the Date.getTime() method to return epoch milliseconds value which is the number of milliseconds since January 1, 1970, 00:00:00 GMT.
  • Using the Timestamp(long time) constructor to instantiate a new Timestamp object from epoch milliseconds value.

In the following example Java code we show how to convert Date object to Timestamp object using the steps above.

ConvertDateToTimestampExample1.java

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

public class ConvertDateToTimestampExample1 {
    public static void main(String... args) {
        // Create new Date object as current date time
        Date date = new Date();

        // Create new Timestamp from Date object
        Timestamp timestamp = new Timestamp(date.getTime());

        System.out.println("Date: " + date);
        System.out.println("Timestamp: " + timestamp);
    }
}
The output as below.
Date: Wed May 18 22:40:38 ICT 2022
Timestamp: 2022-05-18 22:40:38.194

Happy Coding 😊

Java Convert Timestamp to Date

Java Convert Timestamp to Calendar

Java Convert Calendar to Timestamp

Java Convert Timestamp to ZonedDateTime

Java Convert Timestamp to LocalDate

Java Convert Timestamp to Instant

Java Convert Timestamp to OffsetDateTime

Java Convert OffsetDateTime to Timestamp