Java Code:
Timestamp ts = new Timestamp(date.getTime());
Above example command will return the current timestamp and save values in ts object variable.
Advertisement
Java Get TimeStamp
Following example will get the current time in milliseconds using getTime() function. After that Timestamp will convert it to the proper time. The below example is explained in multi-line but if you want the current timestamp only, Use above given one line code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.Date; import java.sql.Timestamp; public class GetTimeStamp { public static void main( String[] args ) { Date date= new Date(); long time = date.getTime(); System.out.println("Time in Milliseconds: " + time); Timestamp ts = new Timestamp(time); System.out.println("Current Time Stamp: " + ts); } } |
After executing the above Java code you will get the following values in return.
Time in Milli Seconds: 1447402821007 Current Time Stamp: 2015-11-13 13:50:21.007
Java Get Date Only
You can use SimpleDateFormat with Calendar class to find the date and time only.
1 2 3 4 5 6 7 8 9 10 11 12 13 | import java.util.Calendar; import java.text.SimpleDateFormat; public class GetTimeStamp { public static void main( String[] args ) { Calendar cal = Calendar.getInstance(); SimpleDateFormat dateOnly = new SimpleDateFormat("MM/dd/yyyy"); System.out.println(dateOnly.format(cal.getTime())); } } |
Output:
02/01/2020
Java Get Time Only
Similarly, you can use SimpleDateFormat with Calendar class to find the time only as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 | import java.util.Calendar; import java.text.SimpleDateFormat; public class GetTimeStamp { public static void main( String[] args ) { Calendar cal = Calendar.getInstance(); SimpleDateFormat timeOnly = new SimpleDateFormat("HH:mm:ss"); System.out.println(timeOnly.format(cal.getTime())); } } |
Output:
15:05:40
5 Comments
nice
can i just get the time, i dont need the date?
More Simple.
Timestamp ts = new Timestamp(System.currentTimeMillis());
System.out.println(“Current Time Stamp: ” + ts);
Works fine, thanks a lot!
Simple and Neat. Good one.