How to Convert Date to Timestamp in Java
The Date class represents a precise moment in time, down to the millisecond. Serializable, Cloneable 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 to a string, whereas parsing entails converting a string to a date. Let us know about How to Convert Date to Timestamp in Java, after the basics of timestamp.
In Java, the Timestamp class may be transformed to a Date class by utilising the Date class. A collection of useful programmes. 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
java.sql.Timestamp
andjava.util.Date
into the class.
- Create a
New Date
classObject
- Now Convert it to TimeStamp using new
Timestamp(date.getTime());
- Print the
Timestamp
.
Also Read: How to convert Double to String in Java
Java Program to Convert Date to Timestamp:
/* * TechDecode Tutorials * * How to Convert Date to TimeStamp * */ import java.sql.Timestamp; import java.util.Date; public class Date_To_Timestamp { public static void main(String args[]) { //Creating Date Object Date date = new Date(); //Converting to TimeStamp Timestamp ts=new Timestamp(date.getTime()); System.out.println(ts); } }
Output: