Monday, January 20, 2025
HomeProgrammingHow Do Java Convert Date to Timestamp?

How Do Java Convert Date to Timestamp?

In Java, you can convert a Date to a Timestamp by creating a Timestamp object that represents the same time as the Date. The Timestamp class is a subclass of java.util.Date and provides nanosecond precision, unlike the Date class which only provides millisecond precision.

Here’s how you can do it:

Code Example:

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

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

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

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

Explanation:

  1. new Date() creates a Date object representing the current time.
  2. date.getTime() gets the time in milliseconds (from the Unix epoch) from the Date object.
  3. new Timestamp(long time) creates a Timestamp object using the milliseconds returned by getTime().

Output:

If you run the code, the output will look something like this (depending on the current date and time):

Date: Sun Jan 20 15:30:45 GMT 2025
Timestamp: 2025-01-20 15:30:45.123

The Timestamp has nanosecond precision (though you may not see the nanoseconds if they are zero in this case).

RELATED ARTICLES

Banking Application in Java

Java PrintWriter Class

What Is CSS Hover?

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x