English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Program to Get Current Date/Time

Kotlin All-in-One Examples

In this program, you will learn how to get the current date and time in different formats in Kotlin.

Example1:Get the current date and time in default format

import java.time.LocalDateTime
fun main(args: Array<String>) {
    val current = LocalDateTime.now()
    println("The current date and time are: $current")
}

When running the program, the output is:

The current date and time are: 2017-08-02T11:25:44.973

In the above program, the current date and time are stored in the variable current using the LocalDateTime.now() method.

For the default format, you just need to use the toString() method to convert it from the LocalDateTime object to a string.

Example2:Get the current date and time using pattern

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS)
    val formatted = current.format(formatter)
    println("The current date and time are: $formatted")
}

When running the program, the output is:

The current date and time are: 2017-08-02 11:29:57.401

In the above program, we defined the format pattern Year-Month-Day Hours:Minutes:Seconds.Milliseconds using DateTimeFormatter object.

Then, we use the format() method of LocalDateTime to use the given formatter. This will get the formatted string output.

Example3:Get the current date and time using predefined constants

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.BASIC_ISO_DATE
    val formatted = current.format(formatter)
    println("The current date is: $formatted")
}

When running the program, the output is:

The current date is: 20170802

In the above program, we used the predefined format constant BASIC_ISO_DATE to get the current ISO date as output.

Example4:Get the current date and time in localized style

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
fun main(args: Array<String>) {
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
    val formatted = current.format(formatter)
    println("The current date is: $formatted")
}

When running the program, the output is:

The current date is: Aug 2, 2017 11:44:19 AM

In the above program, we used the localized style Medium to get the current date and time in the given format. There are other styles: Full, Long, and Short.

Additionally, here is the equivalent Java code:Java Program to Get Current Date and Time

Kotlin All-in-One Examples