How to get current TimeStamp value in Java

Do you know that Java developer Google for even simplest of things? Yes, that's true and I can say it because even I do that :-). The current timestamp value is one of them. In UNIX you can just use the date command to get the current date and time but how do you get that in your Java program? Well, you can get the current timestamp in Java by using Date and Timestamp class of JDK. Note, there is "s" instead of "S" in Timestamp. Since Date in Java contains both date and time, it can be used as Timestamp value as well but when you print Date, it shows time in the local timezone. If you need just the timestamp, then you need to convert the java.util.Date to java.sql.Timestamp. You can convert a Date to Timestamp by using the getTime() method which returns the number of millisecond from the Epoch.

You should also remember that Timestamp is a subclass of java.util.Date but doesn't honor Liskov substitution principle, which means you cannot pass a Timestamp when Date is expected. Why? because it also includes additional nanosecond value which is fitted there to confirm database DATETIME value, which supports nanosecond precision. You can also read my post why Timestamp cannot be used in place of Date in Java for more details.

Btw, In Java 8, you can also use the LocalDateTime class to get the current timestamp in Java. In this article, I'll show you a couple of ways to get the current timestamp value. If you are interested to learn more about new features of Java SE 8 including Date and Time API, lambda expressions, streams, and other small enhancement e.g. joining String using String.join() methods, please see Java SE 8 for Really Impatient By Cay S. Horstmann.





Current Timestamp in Java

Here is a sample code snippet you can use to retrieve the current timestamp value using java.util.Date class and java.sql.Timestamp in Java. Remember the java.util.Date class is named Date, but. it contains both date and time value, unlike LocalDate class of Java 8, which only contains Date information without any time details. There is a separate class LocalTime for representing time without date and LocalDateTime to represent date with time.

On the other hand, java.sql.Timestamp is a subclass of Date but has additional nanosecond value for more precision and be compatible with DATETIME type of many relational database e.g. SQL Server, MySQL, and Oracle.

Anyway, here is our code prior to Java 8 world:

Date now = new java.util.Date();
Timestamp current = new java.sql.Timestamp(now.getTime());
System.out.println("current timestamp: " + current);
System.out.println("current date: " + now);

Output
current timestamp: 2016-06-16 17:33:14.53
current date: Thu Jun 16 17:33:14 SGT 2016

If you run this program, it will print the current date and time value, just try that before you read further.

How to get current timestamp in Java


Btw, if you want your current timestamp into a different String format e.g. "yyyy.MM.dd.HH.mm.ss" then you need to use the SimpleDateFormat class to format the timestamp as shown below:

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(current);
System.out.println("current timestamp as yyyy.MM.dd.HH.mm.ss " + timeStamp);

Output
current timestamp as yyyy.MM.dd.HH.mm.ss 2016.06.16.17.41.19

You can format the date to any way you want, just be aware of the syntax used for formatting dates in Java as shown here.  Btw, these are not the only way to get the current timestamp value, for example, if you just need long milliseconds from the 1st January 1970 then you can use the System.currentTimeMillis() which return millisecond from Epoch and System.nanoTime() which return the current timestamp value in nanoseconds.

 You can also read a good Java book e.g. Core Java for Impatient by Cay S. Horstmann to learn more about fundamentals of Java e.g. date, time, and calendar class in Java. It even covers Java SE 8 new Date and Time API, which is just a bonus.

How to get current TimeStamp value in Java



Java Program to get current Timestamp value

here is our sample Java program to get the current time stamp value. You can run it, tweak it to understand what we are doing. It's simple, we are just converting a date to the timestamp to get the current timestamp value. Later we are formatting into the required format using the SimpleDateFormat class, one of the utility class but be careful it's not thread-safe, see here to learn more about using SimpleDateFormat class in Java.

package test;

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

/**
 * Java Program to get current Timestamp value
 */
public class TimestampTest {

  public static void main(String[] args) {

    Date now = new java.util.Date();
    Timestamp current = new java.sql.Timestamp(now.getTime());
    System.out.println("current timestamp: " + current);
    System.out.println("current date: " + now);

    // printing current timestamp as "yyyy.MM.dd.HH.mm.ss"
    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss")
        .format(current);
    System.out.println("current timestamp as yyyy.MM.dd.HH.mm.ss " + timeStamp);

  }

}

Output
current timestamp: 2016-06-16 17:41:19.305
current date: Thu Jun 16 17:41:19 SGT 2016
current timestamp as yyyy.MM.dd.HH.mm.ss 2016.06.16.17.41.19


That's all about how to get the current timestamp value in Java. Just remember, that Timestamp is a class in the java.sql package and its name include "s" not "S". If you need a long timestamp value then you can also convert a java.util.Date to Timestamp by using getTime() method which return a number of millisecond from Epoch time. Other alternatives include System.currentTimeMillis() which return millisecond from Epoch and System.nanoTime() which return the current timestamp value in nanoseconds.


Other Date and Time tutorials for Java developers
  • How to convert java.sql.Date to java.util.Date in Java? (example)
  • How to format Date in Java using SimpleDateFormat? (example)
  • How to display Date in multiple timezones in Java? (example)
  • How to convert java.util.Date to java.sql.Timestamp in JDBC? (example)
  • How to convert String to Date in Java? (answer)
  • Difference between java.util.Date and java.sql.Timestamp in JDBC? (answer)
  • How to convert java.util.Date to java.sql.Date in JDBC? (answer)
  • How to parse String to Date in Java using JodaTime library? (example)


References
Java SE 8 documentation of Date class
Java Se 8 documentation of Timestamp class



No comments:

Post a Comment