When working with Java, obtaining the current timestamp is crucial for various tasks, such as event logging, managing date and time operations, etc. This can be done using different built-in Java methods, such as System.currentTimeMillis(), Instant.now(), Date() constructor, etc.
In this Java guide, you’ll learn six different approaches to get the current timestamp. Each approach will be discussed along with appropriate examples.
How to Get Current Timestamp in Java
A timestamp is an encoded DateTime format, which demonstrates the occurrence of an event. To get a current timestamp in Java, we can use the methods like “currentTimeMillis()”, “now()”, “Date()” constructor, etc.
Method 1: Getting the Current Timestamp Using System.currentTimeMillis()
The “currentTimeMillis()” is a built-in method of the System class that retrieves the number of milliseconds passed since 1970. These retrieved milliseconds represent the current Timestamp in Java. Here is a simple example that demonstrates the practical implementation of the stated method in Java:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentTS {
public static void main(String[] args) {
//Getting the Current DateTime in Milliseconds
long currentTS = System.currentTimeMillis();
System.out.println("The Current Timestamp in Milliseconds == " + currentTS);
//Converting Milliseconds to Human-readable Date Format
DateFormat formatedTS = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
Date resultantTS = new Date(currentTS);
System.out.println("The Formated Current Timestamp == " + formatedTS.format(resultantTS));
}
}
Code Explanation
- First, we import the required classes like “DateFormat”, “SimpleDateFormat”, and “Date” from their respective packages.
- In the main() method, we invoke the “currentTimeMillis()” method of the System class to get the current timestamp in milliseconds. We store the retrieved milliseconds in a long-type variable named “currentTS”.
- In the next line, we use the println() method to print the current timestamp in milliseconds on the console.
- After this, we use the SimpleDateFormat class to convert the obtained current timestamp in milliseconds to a specific format.
- Next, we invoke the Date() constructor and pass the currentTS to it as an argument. This will convert the milliseconds (long type) to a date instance.
- Finally, we invoke the format() method on the current timestamp to convert it into a specific pattern/format.
Method 2: Getting the Current Timestamp Using the Date Class
We can invoke the constructor of the Date class to get the current DateTime with millisecond precision, as shown in the following code:
import java.util.Date;
public class CurrentTS {
public static void main(String[] args) {
//Getting the Current DateTime
Date currentTS = new Date();
System.out.println("The Current Timestamp == " + currentTS);
//Converting Current Timestamp in Milliseconds
System.out.println("The Current Timestamp in Milliseconds == " + currentTS.getTime());
}
}
Code Explanation
- First, we invoke the Date() constructor to get the current timestamp and println() method to print it on the console.
- In the next line, we invoke the getTime() method on the currentTS instance to convert the current timestamp into milliseconds.
Method 3: Getting the Current Timestamp in Java Using java.time.Instant
Java introduces a new DateTime API in the time package (Instant) that represents a specific instantaneous point on the timeline. This instantaneous point is independent of any specific timezone or calendar. Using the instant class we can store the DateTime values in UTC timezone as well. In the below code snippet, we use the Instant class to get the current timestamp:
import java.time.*;
public class CurrentTS {
public static void main(String[] args) {
//Getting Current DateTime
Instant currentTS = Instant.now();
System.out.println("The Current Timestamp == " + currentTS);
//Converting Current DateTime into Milliseconds
System.out.println("The Current Timestamp in Milliseconds == " + currentTS.toEpochMilli());
}
}
Code Explanation
- First, we import the Instant class from the “time” package and then use it to invoke the now() method to get the current instant. We store the retrieved instant/timestamp in a variable named “currentTS”.
- Next, we invoke the toEpochMilli() method on the currentTS to convert the current instant into milliseconds:
Method 4: Getting the Current Timestamp in Java Using the Timestamp Class
Timestamp is an inbuilt Java class that belongs to the “java.sql” package. We can use the constructor of the stated class to get the current DateTime with millisecond precision, as demonstrated in the below example:
import java.sql.Timestamp;
public class CurrentTS {
public static void main(String[] args) {
Timestamp currentTS = new Timestamp(System.currentTimeMillis());
System.out.println("The Current Timestamp in Milliseconds == " + currentTS.getTime());
//Formating the Current Timestamp
System.out.println("The Formatted Timestamp == " + currentTS.toString())
}
}
Code Explanation
- At the start of the program, we import the Timestamp class from the sql package.
- After this, we pass the “System.currentTimeMillis()” as an argument to the Timestamp() constructor and store the obtained result in the currentTS variable. Then we invoke the getTime() method on the currentTS to retrieve the current DateTime in milliseconds.
- Finally, we use the currentTS with the toString() method to get and print the formatted timestamp on the console:
Method 5: Getting the Current Timestamp in Java Using the LocalDateTime and DateTimeFormatter Classes
We can also get the current timestamp using the now() method of the LocalDateTime class. In addition to this, we can format the obtained current timestamp into a specific pattern using the DateTimeFormatter class. In the following example, first, we get the current timestamp and then we convert it into a specific pattern using the “DateTimeFormatter.ofPattern().format()” method:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentTS {
public static void main(String[] args) {
LocalDateTime currTS = LocalDateTime.now();
System.out.println("The Current Timestamp == " + currTS);
//Formatting Current TimeStamp
String formattedTS = DateTimeFormatter.ofPattern("yyyy/MM/dd - HH:mm:ss").format(currTS);
System.out.println("The Formatted Timestamp == " + formattedTS);
}
}
Code Explanation
- We import the LocalDateTime and DateTimeFormatter classes from the respective packages.
- Next, we use the now() method to get the current/local DateTime.
- After this, we format the obtained DateTime into a specific format using the “ofPattern().format()” method.
- Finally, we print the obtained current timestamp and the formatted timestamp on the console.
Method 6: Getting the Current Timestamp in Java Using the LocalDateTime and ZoneId Classes
The LocalDateTime and ZoneId are built-in classes of the “java.time” package. The LocalDateTime class retrieves the DateTime without timezone information while the ZoneId retrieves the timezone id. We use these classes combined to get the current DateTime with timezone information. Here is an example:
import java.time.*;
import java.time.format.DateTimeFormatter;
public class CurrentTS {
public static void main(String[] args) {
LocalDateTime currDateTime = LocalDateTime.now();
ZoneId id = ZoneId.systemDefault();
ZonedDateTime dateTimeZone = ZonedDateTime.of(currDateTime, id);
//Getting Current Timestamp in Milliseconds
long currentTS = dateTimeZone.toInstant().toEpochMilli();
System.out.println("The Current Timestamp in Milliseconds == " + currentTS);
//Formating the Current Timestamp
DateTimeFormatter formatPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTS = currDateTime.format(formatPattern);
System.out.println("The Formatted Timestamp == " + formattedTS);
}
}
Code Explanation
- Initially, we import the necessary classes like “DateTime”, “ZoneId”, and “ZonedDateTime” from the “java.time” package. Also, we import the DateTimeFormatter class from its respective package to format the current timestamp in a specific format.
- After this, we invoke the “now()” method of the LocalDateTime class to fetch the current DateTime.
- Next, we use the “ZoneId.systemDefault()” method to get the system’s default zone id.
- After this, we use the ZonedDateTime.of() method to represent the DateTime with timezone information.
- Next, we invoke the “toInstant().toEpochMilli()” method on the dateTimeZone instance to retrieve the current timestamp(in milliseconds).
- Then we use the DateTimeFormatter.ofPattern() method to specify a pattern according to which the current timestamp will be formatted.
- Finally, we invoke the format method on the currDateTime instance to format it according to the specified DateTime pattern:
That’s all about Getting a current timestamp in Java.
Final Thoughts
The current timestamp represents the DateTime at the current instance along with the timezone information. To get a current timestamp in Java, we can use methods like “currentTimeMillis()”, “now()”, and the “Date()” constructor. Also, we can use the “Timestamp” class, or “LocalDateTime and ZoneId” Classes to achieve the same purpose. This write-up presented six different methods to get the current timestamp in Java; each method has its pros and cons; you can use the one that best suits your needs.