Java Convert Timestamp to Date

Tags: Java Timestamp Java Date

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

Table of contents

  1. How to convert Timestamp to Date in Java
  2. Convert Timestamp to Date in Java by assign directly

How to convert Timestamp to Date in Java

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

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

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

ConvertTimestampToDateExample1.java

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

public class ConvertTimestampToDateExample1 {
    public static void main(String... args) {
        // Create new Timestamp object as current time
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

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

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

Convert Timestamp to Date in Java by assign directly

As we have the Timestamp class extends the java.util.Date class so that we can assign the Timestamp object directly to Date variable as the Java code below.

ConvertTimestampToDateExample2.java

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

public class ConvertTimestampToDateExample2 {
    public static void main(String... args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        // Convert Timestamp object to Date object
        Date date = timestamp;

        System.out.println("Timestamp: " + timestamp);
        System.out.println("Date: " + date);
    }
}
The output as below.
Timestamp: 2022-05-19 00:07:27.622
Date: 2022-05-19 00:07:27.622

Happy Coding 😊

Java Convert Date to Timestamp

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