How to get current timestamps in Java

Here’s a Java example to show how to get current timestamps in Java.

package com.mkyong.common;
 
import java.sql.Timestamp;
import java.util.Date;
 
public class GetCurrentTimeStamp 
{
    public static void main( String[] args )
    {
	 java.util.Date date= new java.util.Date();
	 System.out.println(new Timestamp(date.getTime()));
    }
}

output

2010-03-08 14:59:30.252
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • http://javahash.com/ Prem Kumar

    My point of view is we should use the Calendar class instead of Date.

  • Kareen Tariman

    This helped. Thanks!

  • huzzlah

    real nice and all, but your output is not a timestamp. a timestamp is the number of seconds since january 1 1970. what you’re creating is some sort of arbitrarily formatted date string.

    get with it, please.

  • pooja

    hello sir/madam,

    I have one problem please help me anyone

    I have hard code date in my java code for 1 min to 8 hours with 6 currency pairs like
    java.sql.Timestamp timestamp = Timestamp.valueOf(“2012-02-24 20:00:00″);
    then its working fine.

    If i have add for live chart like
    java.sql.Timestamp timestamp = new Timestamp(System.currentTimeMillis());

    or
    java.util.Date date= new java.util.Date();
    java.sql.Timestamp timestamp = new Timestamp(today.getTime());

    then its taking lot of time to plot the jfreechart graph .

    so give me some suggestion or any commands need to add in my java code.

    Its urgent please.

    • Ko Lawson

      This is what I have been searching for days. Thanks !
      Both overloaded constructors work great.

  • http://kinesisktolk.dk Morten Slott Hansen

    This is simpler and avoids using Date

    new Timestamp(System.currentTimeMillis());
    • http://mariuzzo.com/ Rubens Mariuzzo

      Love this implementation.

    • Ritvik

      ^^ This is great!

      • Mark Jansen

        This is an awesome solution…..

    • Siddhanta

      Thanks alot

    • Ko Lawson

      This is what I have been searching for days. Thanks !

    • j

      Thanks for this!

      • mkyong

        You’re welcome.

        • Krishna

          i like u r website and how to ask questions