We can convert date to timestamp using the Timestamp class which is present in the sql package.
- The constructor of the time-stamp class requires a long value.
- So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).
Example:
Input: date is 16 November 2020
Output: 2020-11-16 19:11:24Explanation: date would be printed along with the current time to milliseconds.
Approach 1:
- import the java.sql.Timestamp package.
- import the java.util.Date package
- Create an object of the Date class.
- Convert it to long using getTime() method
Syntax:
public long getTime()
Parameters: The function does not accept any parameter.
Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM.
- Create an object of the Timestamp class and pass the value returned by the getTime() method.
- Finally, print this Timestamp object value.
Java
// Java Program to convert date to time stamp import java.sql.Timestamp; import java.util.Date; public class GFG_Article { public static void main(String args[]) { // getting the system date Date date = new Date(); // getting the object of the Timestamp class Timestamp ts = new Timestamp(date.getTime()); // printing the timestamp of the current date System.out.println(ts); } } |
2020-11-19 04:47:43.624
Approach 2:
- We can format the Timestamp value using SimpleDateFormat class.
- Initially, by using the Timestamp class, the time is getting displayed in a standard format, but we can format it to our own choice using SimpleDateFormat class.
Java
// Java program to convert date to time-stamp using // SimpleDataFormat class and TimeStamp class import java.sql.Timestamp; import java.util.Date; import java.text.SimpleDateFormat; public class GFG { public static void main(String args[]) { // getting the system date Date date = new Date(); // getting the timestamp object Timestamp ts = new Timestamp(date.getTime()); // using SimpleDateFormat class,we can format the // time-stamp according to ourselves // getting the timestamp upto sec SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); System.out.println(formatter.format(ts)); // getting the timestamp to seconds SimpleDateFormat formatter1 = new SimpleDateFormat( "yyyy-MM-dd HH:mm" ); // printing the timestamp System.out.println(formatter1.format(ts)); } } |
2020-11-19 04:52:31 2020-11-19 04:52
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.