beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to get current timestamp in java

By Chaitanya Singh | Filed Under: Java Date

Its quite easy to get the current timestamp in java. In this tutorial we will see how to get the timestamp using Date and Timestamp class.

Here are the steps that we have followed in the below example:
1) Created the object of Date class.
2) Got the current time in milliseconds by calling getTime() method of Date.
3) Created the object of Timtestamp class and passed the milliseconds that we got in step 2, to the constructor of this class during object creation. It constructs the timestamp using the provided milliseconds value.

import java.sql.Timestamp;
import java.util.Date;

public class TimeStampDemo 
{
    public static void main( String[] args )
    {
         //Date object
	 Date date= new Date();
         //getTime() returns current time in milliseconds
	 long time = date.getTime();
         //Passed the milliseconds to constructor of Timestamp class 
	 Timestamp ts = new Timestamp(time);
	 System.out.println("Current Time Stamp: "+ts);
    }
}

Output:

Current Time Stamp: 2014-01-08 18:31:19.37

References:

  • Javadoc – Date
  • Timestamp docs

Enjoyed this post? Try these related posts

  1. Java calendar class: add/subtract Year, months, days, hour, minutes
  2. Java SimpleDateFormat Class explained with examples
  3. How to get current day, month, year, day of week/month/year in java
  4. How to get current date and time in java
  5. Java date difference
  6. Java Date – Convert 12 hour format to 24 hour format and vice versa

Leave a Reply Cancel reply

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

Java Date and Time

  • Java Date Time
  • Java LocalDate
  • Java LocalTime
  • Java LocalDateTime
  • Java ZonedDateTime
  • Java DateTimeFormatter
  • current date time

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap