In the previous article we have discussed Java Program to Convert Date to String
In this article we will see how to convert a date to timestamp.
Program To Convert Date To Timestamp
Let’s see different ways to do it.
Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.
Method 1 : Java Program to Convert Date to Timestamp Using geTime() method
Approach :
- Take the instant date and time through inbuild function new
Date()
, store it in a variable lets say “d
”. - Convert the date into the timestamp using
getTime()
method and store it in variableoutput
. - Print the result .
Program :
import java.sql.Timestamp; import java.util.Date; public class Main { public static void main(String args[]) { // taking the instant date Date d = new Date(); // converting to Timestamp Timestamp output = new Timestamp(d.getTime()); System.out.println("Converted date String: " + output); } }
Output : Converted date String: 2021-09-07 11:18:53.467
Method 2 : Java Program to Convert Date to Timestamp Using SimpleDateFormat class
Approach :
- Take the instant date and time through inbuild function new
Date()
,store it in a variable lets say “d
”. - Convert it to the time stamp .
- Define the format of the time stamp .
- Print the result .
Program :
import java.sql.Timestamp; import java.util.Date; import java.text.SimpleDateFormat; public class Main { public static void main(String args[]) { // taking the instant date Date d = new Date(); // converting to Timestamp Timestamp t = new Timestamp(d.getTime()); // define the format of the date SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // printing the result System.out.println("Converted date String: " + f.format(t )); } }
Output : Converted date String: 2021-09-07 11:18:53.467
Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.
Related Java Program: