Kotlin program to get the current time in milliseconds

Why 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 local 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.

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 some 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 example.

In this post, I am listing down two different ways to get the current milliseconds in Kotlin. Just go through the examples and drop one comment below if you have any questions.

Method 1 : Using currentTimeMillis() :

currentTimeMillis is defined in System.java. 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();

The return value is long.

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

Method 2: Using the Calendar class :

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

import java.util.Calendar

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

Combining two :

import java.util.Calendar

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

Execute it. You will get output something like below :

1579886694096
1579886694114

There is a small difference because the execution of println takes some time.

Kotlin print milliseconds