How to Convert Timestamp to Date in Java

Java is an object-oriented programming language that produces software for multiple platforms. The Date class represents a precise moment in time, down to the millisecond. SerializableCloneable and Comparable interfaces are implemented by the Date class in the java. util package. It has constructors and methods for working with dates and times in Java. In Java, the “java.text.SimpleDateFormat” class has methods for formatting and parsing date and time. The “SimpleDateFormat” is a concrete class that inherits the “java. text. DateFormat” class for formatting and parsing dates. It’s interesting to note that formatting entails turning a date into a string, whereas parsing entails converting a string to a date. Let us know about How to Convert Timestamp to Date in Java, after the basics of timestamp.

The Date class’s function Object()  takes a long value as a parameter. Because the Date class’s function Object() {  } requires a long value, we must convert the Timestamp object to a long number using the TimeStamp class’s getTime() function (present in SQL package).

 

What’s the Approach?

 

  • Import the java.sql.Timestamp and java.util.Date package into the class.

 

  • Create a new TimeStamp object with getting the System's current time

 

  • Convert the timestamp to date using new Date(ts.getTime());

 

  • Print the Date.

 

Also Read: How to convert String to float in Java

 

Java Program to Convert Timestamp to Date:

/*

 * TechDecode Tutorials

 *

 * How to Convert TimeStamp to Date

 *

 */

import java.sql.Timestamp;   

import java.util.Date;   

public class Timestamp_To_Date

{   

    public static void main(String args[])

    {

        //Creating a New TimeStamp

        Timestamp ts=new Timestamp(System.currentTimeMillis());

        //Converting to Date

        Date date=new Date(ts.getTime()); 

        System.out.println(date);                    

    }   

}

 

Output:

 

Timestamp to Date

Leave a Reply

Your email address will not be published. Required fields are marked *