Java Timestamp getTime()

In this guide, you will learn about the Timestamp getTime() method in Java programming and how to use it with an example.

1. Timestamp getTime() Method Overview


The getTime() method of the Timestamp class in Java returns the time represented by the Timestamp object in milliseconds since January 1, 1970, 00:00:00 GMT (the epoch).


public long getTime()


This method does not accept any parameters.

Key Points:

- The Timestamp class is part of the java.sql package, and this class extends java.util.Date.

- The getTime() method is useful when there is a need to compare timestamps or calculate the difference between two timestamps.

- The returned value is a long representing the time in milliseconds since the epoch.

- This method is used for interoperability with java.util.Date or converting to other time units.

2. Timestamp getTime() Method Example

import java.sql.Timestamp;

public class TimestampExample {
    public static void main(String[] args) {
        // Creating a Timestamp object for the current time
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        // Printing the original Timestamp object
        System.out.println("Original Timestamp: " + timestamp);

        // Getting the time in milliseconds since the epoch
        long timeInMillis = timestamp.getTime();

        // Printing the time in milliseconds
        System.out.println("Time in Milliseconds: " + timeInMillis);

        // Calculating the difference in time between two Timestamps
        Timestamp earlierTimestamp = new Timestamp(System.currentTimeMillis() - 10000); // 10 seconds earlier
        long differenceInMillis = timestamp.getTime() - earlierTimestamp.getTime();
        System.out.println("Difference in Milliseconds: " + differenceInMillis);


Original Timestamp: 2023-09-20 12:45:30.123456789
Time in Milliseconds: 1671117930123
Difference in Milliseconds: 10000


In this example, we first created a Timestamp object representing the current time and printed it. We then used the getTime() method to get the time in milliseconds since the epoch and printed it. Lastly, we calculated and printed the difference in milliseconds between two Timestamp objects, demonstrating the usefulness of the getTime() method in time calculations.