📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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: 1690263327269
In 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: 1690263404149
Conclusion
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.
Comments
Post a Comment
Leave Comment