In this article, we will see different methods to get the current timestamp in Kotlin.

currentTimeMillis():

By using the system.currentTimeMillis(), we can get the current timestamp in Kotlin. This function returns the current time in milliseconds since January 1, 1970, which is also known as the Unix epoch.

Following is the example:

val currentTimeMillis = System.currentTimeMillis()
println("Current Timestamp in milliseconds: $currentTimeMillis")

Instant.now()

We can also use the Instant.now() the method from the java.time package to get the current timestamp. It provides a more modern approach to working with dates and times.

Following is the example:

import java.time.Instant

val currentInstant = Instant.now()
println("Current Timestamp using Instant: $currentInstant")

Convert the current timestamp to the localDateTime format

Once we have the current timestamp, Using java.time we can convert it into a specific date and time format for better readability.

import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId

val currentInstant = Instant.now()
val currentDateTime = LocalDateTime.ofInstant(currentInstant, ZoneId.systemDefault())
println("Current Date and Time: $currentDateTime")

In the above example, using the Instant.now() function we are getting the current timestamp. Then, the LocalDateTime.ofInstant() method is called to convert the Instant object to a LocalDateTime object, using the system’s default time zone. Finally, the converted LocalDateTime value is printed.

Categorized in:

Tagged in:

,