How to get the Unix timestamp in Java
Table of Contents
In the field of computer science, there is a concept of the unix timestamp, also known as the posix time or epoch time. This timestamp is defined as the number of seconds that have elapsed since January 1, 1970.
This is useful because it allows us to express dates and time in a single number as opposed to having to store the day, month, year, hour, minutes and seconds separately.
In this post, we'll learn all the different ways to get the unix timestamp in Java.
Instant
Java introduced a new API for date and time to replace the old Date class. This is thread-safe and immutable, among other useful improvements.
Here's how to get the current time in Java using the Instant class:
JAVAlong time = Instant.now().getEpochSecond();
You can then take this number and convert it to a date and time using the Instant class:
JAVAlong time = Instant.now().getEpochSecond();
Instant instant = Instant.ofEpochSecond(time);
With the Instant class, you can then call any method on the Instant class to get any additional piece of information that you want.
System.currentTimeMillis()
The original way to get the unix timestamp in Java was to use the System.currentTimeMillis()
method. This method returns the number of milliseconds that have elapsed since the epoch time. From there you can just use simple division to get the number of seconds.
JAVAlong time = System.currentTimeMillis() / 1000;
Remember that this is only useful for when you're on Java 7 or lower, since in Java 8, you can use the much-improved Instant class.
Date
The final way to get the unix timestamp in Java is to use the Date class. This class is not thread-safe, and is not immutable, so only use it if you are on Java 7 or lower.
Here's how to use the Date class to get the unix timestamp:
JAVADate date = new Date();
long time = date.getTime() / 1000;
Conclusion
In this post, we explored three different ways to get the unix timestamp in Java.
Basically, if you are on a modern version of Java, you should use the Instant class, otherwise, you should use the Date class.
Hopefully, you've found this post helpful! Happy coding!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React