Find number of seconds elapsed since Unix epoch in Kotlin
This article explores different ways to find the number of seconds elapsed since the Unix epoch in Kotlin. The Unix epoch (or Unix time or Epoch time or Posix time) is the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC.
1. Using System.currentTimeMillis() function
The simplest way is probably using the System.currentTimeMillis() function that returns the difference between the current time and Unix epoch in “milliseconds”. This is demonstrated below:
|
1 2 3 4 |
fun main() { val ms = System.currentTimeMillis() println(ms) } |
Output (will vary):
1640882619680
To get the number of “seconds” elapsed since the Unix epoch, we can simply divide the return value of the System.currentTimeMillis() function by 1000.
|
1 2 3 4 |
fun main() { val timestamp = System.currentTimeMillis() / 1000 println(timestamp) } |
Output (will vary):
1640882633
2. Using Instant.toEpochMilli() function
The java.time.Instant class represents an instantaneous point on the time-line. We can get the current instant using the Instant.now() function and convert this instant to the number of seconds from the Unix epoch with epochSecond.
|
1 2 3 4 5 6 |
import java.time.Instant fun main() { val timestamp = Instant.now().epochSecond println(timestamp) } |
Output (will vary):
1640882923
Additionally, we can convert the current instant to the number of milliseconds from the epoch using the toEpochMilli() function.
|
1 2 3 4 5 6 |
import java.time.Instant fun main() { val ms = Instant.now().toEpochMilli() println(ms) } |
Output (will vary):
1640882923772
That’s all about finding the number of seconds elapsed since the Unix epoch in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)