Main Tutorials

How to get current timestamps in Java

This article shows few Java examples to get the current date time or timestamp in Java. (Updated with Java 8).

Code snippets


  // 2021-03-24 16:48:05.591
  Timestamp timestamp = new Timestamp(System.currentTimeMillis());

  // 2021-03-24 16:48:05.591
  Date date = new Date();
  Timestamp timestamp2 = new Timestamp(date.getTime());

  // convert Instant to Timestamp
  Timestamp ts = Timestamp.from(Instant.now())

  // convert ZonedDateTime to Instant to Timestamp
  Timestamp ts = Timestamp.from(ZonedDateTime.now().toInstant()));

  // convert Timestamp to Instant
  Instant instant = ts.toInstant();

Table of contents

1. Java Timestamp examples

The below program uses java.sql.Timestamp to get the current timestamp and format the display with SimpleDateFormat.

TimeStampExample.java

package com.mkyong.app;

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

public class TimeStampExample {

    // 2021.03.24.16.34.26
    private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");

    // 2021-03-24T16:44:39.083+08:00
    private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

    // 2021-03-24 16:48:05
    private static final SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {

        // method 1
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println(timestamp);                      // 2021-03-24 16:34:26.666

        // method 2 - via Date
        Date date = new Date();
        System.out.println(new Timestamp(date.getTime()));  // 2021-03-24 16:34:26.666
                                                            // number of milliseconds since January 1, 1970, 00:00:00 GMT
        System.out.println(timestamp.getTime());            // 1616574866666

        System.out.println(sdf1.format(timestamp));         // 2021.03.24.16.34.26

        System.out.println(sdf2.format(timestamp));         // 2021-03-24T16:48:05.591+08:00

        System.out.println(sdf3.format(timestamp));         // 2021-03-24 16:48:05

    }
}

Output

Terminal

2021-03-24 16:48:05.591
2021-03-24 16:48:05.591
1616575685591
2021.03.24.16.48.05
2021-03-24T16:48:05.591+08:00
2021-03-24 16:48:05

2. Convert Instant to/from Timestamp

This example shows how to convert the new Java 8 java.time.Instant to and from the legacy java.sql.Timestamp.


  // convert Instant to Timestamp
  Timestamp ts = Timestamp.from(Instant.now())

  // convert Timestamp to Instant
  Instant instant = ts.toInstant();
InstantExample.java

package com.mkyong.app;

import java.sql.Timestamp;
import java.time.Instant;

public class InstantExample {

  public static void main(String[] args) {

      Timestamp timestamp = new Timestamp(System.currentTimeMillis());
      System.out.println(timestamp);                  // 2021-03-24 17:12:03.311
      System.out.println(timestamp.getTime());        // 1616577123311

      // Convert Timestamp to Instant
      Instant instant = timestamp.toInstant();
      System.out.println(instant);                    // 2021-03-24T09:12:03.311Z
      System.out.println(instant.toEpochMilli());     // 1616577123311

      // Convert Instant to Timestamp
      Timestamp tsFromInstant = Timestamp.from(instant);
      System.out.println(tsFromInstant.getTime());    // 1616577123311
  }
}

Output

Terminal

2021-03-24 17:12:03.311
1616577123311
2021-03-24T09:12:03.311Z
1616577123311
1616577123311

3. Insert Timestamp into a table

The java.sql.Timestamp is still widely used in JDBC programming. See the below conversions:


  // Java 8, java.time.*

  // convert LocalDateTime to Timestamp
  preparedStatement.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));

  // convert Instant to Timestamp
  preparedStatement.setTimestamp(1, Timestamp.from(Instant.now()));

  // Convert ZonedDateTime to Instant to Timestamp
  preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant()));

The below example is a JDBC example of inserting a Timestamp into the table.

JdbcExample.java

package com.mkyong.app;

import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDateTime;

public class JdbcExample {

  private static final String SQL_INSERT = "INSERT INTO EMPLOYEE (NAME, SALARY, CREATED_DATE) VALUES (?,?,?)";

  public static void main(String[] args) {

      try (Connection conn = DriverManager.getConnection(
              "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
           PreparedStatement preparedStatement = conn.prepareStatement(SQL_INSERT)) {

          preparedStatement.setString(1, "mkyong");
          preparedStatement.setBigDecimal(2, new BigDecimal("799.88"));
          preparedStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));

          // preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant()));
          // preparedStatement.setTimestamp(3, Timestamp.from(Instant.now()));

          int row = preparedStatement.executeUpdate();

          // rows affected
          System.out.println(row); //1

      } catch (SQLException e) {
          System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
      } catch (Exception e) {
          e.printStackTrace();
      }

  }
}

4. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Latest Tutorials
9 years ago

For Sql date and Time Stamp

java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement.setTimestamp(1, timestamp);

Ajay Singh
1 year ago

Thanks Dude. Your small code snippets must have helped millions of developers. I use them all the time.

joseph
9 years ago

I really love your blog my friend it saved my live so much time thanks a lot for what you do sincerly yours 🙂

pooja
12 years ago

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
11 years ago
Reply to  pooja

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

Kareen Tariman
11 years ago

This helped. Thanks!

huzzlah
11 years ago

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.

mkyong
7 years ago
Reply to  huzzlah

Article is updated, to return the number of seconds since january 1 1970, use this timestamp.getTime()