How to get the current local date and time in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

Kotlin is a statistically typed language and it is based on Java, hence all the Java codes can easily be compiled within Kotlin. In this article, we will see how we can generate the current local date and time in Kotlin.

As Kotlin is interoperable with Java, we will be using the Java utility class and Simple Date Format class in order to get the current local date and time.

Example – Current Date and time using SimpleDateFormat

import java.text.SimpleDateFormat
import java.util.*

fun main(args: Array<String>) {
   val simpleDate = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
   val currentDate = simpleDate.format(Date())
   println(" Current Date is: " +currentDate)
}

Output

On execution, it will generate the current Date and Time. Note that the following output is Server date and time, hence it will be different when you run this code on your system.

Current Date is: 28/2/2022 12:58:59

Example – Current Date Time using LocalDateTime

There is another class "LocalDateTime" that can be used for generating the local date and time.

import java.time.LocalDateTime
fun main(args: Array<String>) {
   val current = LocalDateTime.now()
   println("Current Date and Time is: $current")
}

Output

Once executed, it will yield the following output −

Current Date and Time is: 2022-02-28T13:00:13.027
raja
Updated on 01-Mar-2022 12:07:10

Advertisements