Tuesday, March 19, 2024

How to get current TimeStamp value in Java? Example

Do you know that Java developer Google (now ask ChatGPT) for even the simplest of things? Yes, that's true and I can say it because even I do that :-). Finding 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 the 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 a 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 a Timestamp by using the getTime() method which returns the number of milliseconds from the Epoch.

You should also remember that Timestamp is a subclass of java.util.Date but doesn't honor the Liskov substitution principle, which means you cannot pass a Timestamp when Date is expected.

Why? because it also includes an additional nanosecond value which is fitted there to confirm database DATETIME value, which supports nanosecond precision. You can also read my post on 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 enhancements like joining String using the  String.join() methods, please see these free Java 8 tutorials and courses



How to get Current Timestamp in Java? Example

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 the 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 an additional nanosecond value for more precision and be compatible with the DATETIME type of many relational databases 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.

ow to get current TimeStamp value in Java? Example


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 join these free Java Programming courses to learn more about the 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.



Java Program to get current Timestamp value

here is our sample Java program to get the current timestamp 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 classes 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 includes "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 returns a number of milliseconds 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 the JodaTime library? (example)
Thank you guys for reading this tutorial so far. If you have any questions or doubt feel free to ask in comments. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.