Kotlin program to get the current time in milliseconds

Why do you need time in milliseconds?

The current time is different in different parts of the world. And it is not a good practice to use the local system time in an application. You can either store the time in UTC and convert it to different locals or you can store the milliseconds counted from a specific date-time. We can store this value in the backend and it can be converted back to date-time based on the device locale.

The Unix time/Unix timestamp/epoch/POSIX time is the number of seconds that have elapsed since January 1, 1970(midnight UTC/GMT). We can get this time as milliseconds in Kotlin, Java or any other languages.

If you are tracking any user events like how much time a user has spent after the first start, you can store the start time and end time as milliseconds. This is just one of the simplest use cases.

In this post, I am listing down two different ways to get the current milliseconds in Kotlin.

Method 1: By using the currentTimeMillis() method:

The currentTimeMillis() method is defined in the System.java class. It returns the current time or difference between the current time and midnight, January 1, 1970, UTC in milliseconds. This method is defined as below:

public static native long currentTimeMillis();

It is a static method and we don’t need to create any object of the System class to call it. The return value is long. We can use this method as below:

fun main() {
    println(System.currentTimeMillis())
}

Method 2: By using the Calendar class:

Calandar.java is another Java class. The Calendar.java class provides time-related methods. This class is defined in the java.util package. To get the current time in milliseconds, we can simply create one instance of the Calendar class and we can read the timeInMillis value. It will give us the current epoch time.

import java.util.Calendar

fun main() {
    val calendar = Calendar.getInstance()
    println(calendar.timeInMillis)
}

Combining the above two methods:

The following code uses both of the above two methods:

import java.util.Calendar

fun main() {
    val calendar = Calendar.getInstance()
    println(calendar.timeInMillis)
    println(System.currentTimeMillis())
}

Download the program on Github

If you run this program, it will print the output as below:

1579886694096
1579886694114

There is a slight difference between the time output because of the execution time of println.

Kotlin print milliseconds

You might also like: