The concept of "Epoch Time" is frequently used in programming. It's especially common in scenarios where time and date need to be stored in a format that is easily sortable and comparable.
How to Get Epoch Time in Java 8
Java 8 introduced a new Date-Time API (java.time) that is comprehensive and more user-friendly, superseding the old date-time classes like java.util.Date and java.util.Calendar. We can now get the current epoch time in seconds or milliseconds using this API.import java.time.Instant;
public class Main {
public static void main(String[] args) {
// Get the current epoch time in seconds
long epochSeconds = Instant.now().getEpochSecond();
System.out.println("Epoch in Seconds: " + epochSeconds);
// Get the current epoch time in milliseconds
long epochMilliseconds = Instant.now().toEpochMilli();
System.out.println("Epoch in Milliseconds: " + epochMilliseconds);
}
}Epoch in Seconds: 1690263295
Epoch in Milliseconds: 1690263295605- getEpochSecond(): This method returns the current time in epoch seconds. It's equivalent to System.currentTimeMillis() / 1000L.
- toEpochMilli(): This method returns the current time in epoch milliseconds. It's equivalent to System.currentTimeMillis().
How to Get Epoch Time in Java (Older version)
import java.util.Date;
public class Main {
public static void main(String[] args) {
// Get the current epoch time in milliseconds
long epochMilliseconds = new Date().getTime();
System.out.println("Epoch in Milliseconds: " + epochMilliseconds);
}
}Output:
Epoch in Milliseconds: 1690263327269In this code snippet, new Date().getTime(); returns the current time in epoch milliseconds.Get the Current Timestamp in Java using System.currentTimeMillis()
import java.util.Date;
public class Main {
public static void main(String[] args) {
// Get epoch timestamp using System.currentTimeMillis()
long currentTimestamp = System.currentTimeMillis();
System.out.println("Current epoch timestamp in millis: " + currentTimestamp);
}
}Output:
Current epoch timestamp in millis: 1690263404149Conclusion
In this blog post, we discussed different ways to get the current epoch timestamp in seconds and milliseconds of precision using Java and Java 8 API.
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment