Every operation performed by the system depends on the time and date factor to perform each assigned task on schedule. This prevents any type of data lossage or errors. The date and timestamp are assigned to every System task from the creation of a new file to the sending of an email. This timestamp is assigned by the system clock to operate more sequentially. By the usage of some methods, the developer can retrieve the assigned timestamp.

This guide explains the mentioned approaches to get the current timestamp in Java:

  • Method 1: Use of “System.currentTimeMillis()” to get a Current Timestamp
  • Method 2: Use of “java.time.Instant” to get a Current Timestamp
  • Method 3: Use of “LocalDateTime” and “DateTimeFormatter”
  • Method 4: Use of “Date” Class and “getTime()” Method
  • Method 5: Use of “java.time.LocalDateTime” and “java.time.ZoneId” Packages
  • Method 6: Use of “java.sql.Timestamp” Package to Get Current Timestamp
  • Bonus Tip: Convert Instant to or from the Timestamp
  • Conclusion

How to Get the Current Timestamp in Java?

The “timestamp” is an encoded format of time, date or both showing the time interval for the specified task. These assigned timestamps are very helpful in the profiling, logging, or calling methods in specific schedules.

Let’s have a practical implementation of approaches that can be used to get the current timestamp in Java.

Method 1: Use the “System.currentTimeMillis()” to get a Current Timestamp

The “currentTimeMillis()” method of the “java.lang.System” class retrieves the execution time for the current System process in milliseconds:

class javabeat{
public static void main(String[] args) {
  long currentTimeVar = System.currentTimeMillis();
  System.out.println("The Retrieved Current Timestamp in milliseconds is: " + currentTimeVar);
}
}

The above code shows that:

  • First, the class “javabeat” is created that contains a “main()” method. 
  • Inside this method, the “currentTimeMillis()” method of the “System” class is invoked. The generated result is then stored in the “long” type “currentTimeVar” variable.
  • Finally, this variable is displayed on the console window for verification purposes.

The output shows that the current process “timestamp” data has been retrieved:

Method 2: Use of “java.time.Instant” to get a Current Timestamp

The “java.time.Instant” class represents an instantaneous position on the timeline. This position helps in getting the information related to currently running processes. This class offers a “toEpochMilli()” method to convert the retrieved timestamp into milliseconds. As shown below:

import java.time.Instant;

class javabeat{
public static void main(String[] args) {
  Instant currentTimeVar = Instant.now();
  System.out.println("\nThe Retrieved Current Timestamp in milliseconds is: " + currentTimeVar.toEpochMilli());
}
}

The above code is explained as follows:

  • First, import the “java.time.Instant” package and define a custom class named “javabeat”. This class contains a “main()” method as well. 
  • Next, select the currently executing process from UTC(Coordinated Universal Time) clock by invoking the “Instant.now()” method. The retrieved value is stored in the new instance of the “Instant” class namely “currentTimeVar”.
  • After that, to retrieve timestamp data in milliseconds the “toEpochMilli()” method is applied to the “currentTimeVar” variable.

The result of the above code shows that the current “timestamp” is retrieved in Java:

Method 3: Use of “LocalDateTime” and “DateTimeFormatter”

To retrieve the timestamp containing both date and time for the current System process the “LocalDateTime” class will be used. The retrieved timestamp can then be formatted according to the desired formation using the methods provided by the “DateTimeFormatter” class:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class javabeat{
public static void main(String[] args) {
  //time and date Timestamp Retriever
  LocalDateTime dateTimeStamp = LocalDateTime.now();
  String currentTimeVar = DateTimeFormatter.ofPattern("dd/MM/yyyy; HH:mm:ss").format(dateTimeStamp);
  System.out.println("\nThe Retrieved Timestamp With both Date and Time is: " + currentTimeVar);
}
}

The explanation of above code is as follows:

  • First, import the “java.time.LocalDateTime” and “java.time.format.DateTimeFormatter” packages. Then, define a “main()” method inside the custom-created class namely “javabeat”.
  • Next, create a new instance of the “LocalDateTime” class named “dateTimeStamp”. It stores the current timestamp data which is retrieved using the “now()” method.
  • After that, set the pattern of a timestamp by passing the desired date and time pattern in the “DateTimeFormatter.ofPattern()” method.
  • Now, to apply this pattern over the retrieved timestamp, pass the “dateTimeStamp” as an argument in the “format()” method.
  • Store the returned result in the String type “currentTimeVar” variable which is then displayed on the console.

The output for the above code shows that the timestamp having both a date and time parts are retrieved:

Method 4: Use of “Date” Class and “getTime()” Method

The “Date” class selects the timestamp of a currently executing System process. The selected data contains both the date and time part of the timestamp. In addition, the “getTime()” method is used over the retrieved data to select only the “time” part from the timestamp in milliseconds. 

import java.util.Date;
class javabeat{
public static void main(String[] args) {
  Date currentDate = new Date();
  System.out.println("The Retrieved Current Timestamp in Milliseconds is: " + currentDate.getTime());
}
}

The explanation of the above code snippet, is as follows:

  • First, import the required “java.util.Date” package using the “import” keyword.
  • Then, create a custom class named “javabeat” and define a “main()” method inside it.
  • In this method, create a new instance of the “Date” class namely “currentDate”.
  • Now, apply the “getTime()” method on the “currentDate” instance to get the timestamp in milliseconds.
  • Finally, display the returned results from the “getTime()” method on the console.

The output confirms the retrieval of the timestamp in Java:

Method 5: Use of “java.time.LocalDateTime” and “java.time.ZoneId” Packages

In this method, the “LocalDateTime” and “ZoneId” packages are used in combination to retrieve timestamps along with their time zone. To decrease any sort of ambiguity related to time zones:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

class javabeat{
public static void main(String[] args) {
  LocalDateTime ldtObj = LocalDateTime.now();
  ZoneId defZoneId = ZoneId.systemDefault();
  ZonedDateTime zonedObj = ZonedDateTime.of(ldtObj, defZoneId);

  long currTimestamp = zonedObj.toInstant().toEpochMilli();
  DateTimeFormatter formatTimeDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  String timestampformat = ldtObj.format(formatTimeDate);
  System.out.println("The Retrieved Current Timestamp in Milliseconds is: " + currTimestamp);
  System.out.println("\nThe Timestamp in Formatted Version With Date: " + timestampformat);
}
}

The above code works like this:

  • First, import the “LocalDateTime”, “ZoneId”, “ZonedDateTime”, and “DateTimeFormatter” utilities from a single “java.time” package.
  • Next, create new instances of “LocalDateTime” and “ZoneId” classes namely “idtObj” and “defZoneId”. The instances store the data for the current time interval and the default time zone according to the current time.
  • Now, pass both instances as a parameter in the “ZonedDateTime.of()” method.
  • After that, invoke the “toInstant().toEpochMilli()” method to convert the retrieved timestamp in milliseconds. The generated result is then stored in the “currTimestamp” variable.
  • Moreover, use the “DateTimeFormatter” class “ofPattern()” and “format()” methods to set a specific pattern of the retrieved timestamp.
  • After formatting the retrieved timestamp, store it in a String type variable named “timestampformat”.
  • Finally, print the “timestampformat” on the console for verification purposes.

The output shows that the current timestamp in milliseconds and with “data” are retrieved:

Method 6: Use of “java.sql.Timestamp” Package to Get Current Timestamp

The “java.sql.Timestamp” package acts as a wrapper class around the “java.util.Date” that allows the JDBC to identify as an SQL TIMESTAMP value. This package is recommended for users who use Java 7 and below. The mentioned package represents a date-time value and is hence suitable for the retrieval of the current System process timestamp as well. As shown in the below code snippet:

import java.sql.Timestamp;
class javabeat{
public static void main(String[] args) {

  Timestamp currTimeStamp = new Timestamp(System.currentTimeMillis());

  System.out.println("\nThe Retrieved Current Timestamp in Milliseconds is: " + currTimeStamp.getTime());
  System.out.println("\nThe Timestamp in Formatted Version With Date: " + currTimeStamp.toString());
}
}

The above code works like this:

  • First, import the “java.sql.Timestamp” package and create a class “javabeat”. This class contains a “main()” method as well.
  • Next, create a “currTimeStamp” named instance of the “Timestamp” class. Then, pass the “System.currentTimeMillis()” method as a parameter for this class constructor.
  • The timestamp in milliseconds is then retrieved for the current System process by applying the “getTime()” method on the “currTimeStamp” instance.
  • Finally, to retrieve the data and time part of the timestamp in readable format apply the “toString()” method to the same instance.

The output confirms that the timestamp in milliseconds and String format is retrieved:

Bonus Tip: Convert Instant to or from the Timestamp

This section deals with the conversion of timestamp data from “java.time.Instant” to “java.sql.Timestamp” and vice versa. As we already know, the “java.time.Instant” is used in modern projects that work on Java version “8” and the “java.sql.Timestamp” is for Java version “7” and below. The conversion from the older version to or from the latest version is useful for maintaining or analyzing the legacy code. 

The code of conversion in Java is mentioned below:

import java.sql.Timestamp;
import java.time.Instant;
class javabeat{
public static void main(String[] args) {
  //Get Timestamp from Instant
  Instant fromInstant = Instant.now();
  Timestamp toTimeStamp = Timestamp.from(fromInstant);
  System.out.println("\nThe Process Timestamp After converting from Instant To sql.Timestamp is:\n " + toTimeStamp);

//Get Instant from Timestamp
  Timestamp fromTimestamp2 = new Timestamp(System.currentTimeMillis());
  Instant toInstant2 = fromTimestamp2.toInstant();
  System.out.println("\nThe Process Timestamp After converting from sql.Timestamp To Instant is:\n " + toInstant2);
}
}

The description of the above code is as follows:

  • First, the “Timestamp” and “Instant” packages are imported into the current Java file using the “import” keyword.
  • Next, a new instance named “fromInstant” for the “Instant” class is created for the current time using a “now()” method. 
  • Then, this “Timestamp” class instance is created with the name “toTimeStamp”.
  • For conversion, the “fromInstant” instance is passed as a parameter for the “from()” method at the time of instance creation.
  • After that, create a new instance named “fromTimestamp2” of the “Timestamp” class. It stores the timestamp for the current process using the “System.currentTimeMillis()” method.
  • To convert the created instance into an “Instant” version, create a new instance for “Instant” namely “toInstant2”. This instance stored the converted version of a timestamp by the utilization of the “toInstant()” method on the “fromTimestamp2” instance.

The output confirms the conversion from the Instant to the Timestamp class and from the Timestamp to Instant class:

That’s all about the retrieval of a current timestamp in Java.

Conclusion

To get the current timestamp in Java, use the “System.currentTimeMillis()” method, “java.time.Instant” class “now()” and “toEpochMilli()” methods, “LocalDateTime” and “DateTimeFormatter” class “ofPattern()” and “format()” methods. Also, use the methods provided by the “java.time.ZoneId”, “Date”, and “java.sql.Timestamp” packages. In addition, the timestamp can be converted from “Instant” to “sql.Timestamp” version using the “from()” method and vice versa using the “toInstant()” method. This guide has explained the procedure to get the current timestamp in Java.