X

How To Format Date Time In Kotlin

Kotlin Date Time Formatting


Overview Patterns Kotlin Date Time Examples


Overview

Kotlin is a programming language that allows you to write Android apps and program “happier”.  Chances are if you are developing a mobile app for Android-based phones, tablets and watch you’ll need to learn Kotlin.  Date Time Formatting in Kotlin is based on the SimpleDateFormat class and also the DateTimeFormatter class which was added in API level 26. This not at all different from SimpleDateFormat class that is used in Java 7 and the DateTimeFormatter class that is used in Java 8.

Patterns

If you are using an API level less than 26, please visit our Java7 Patterns Documentation.

If you are using an API level 26 or greater, please visit our Java 8 Patterns Documentation.

 

Kotlin Date Time Formatting Examples

For Kotlin API levels less than 26, here is a Kotlin SimpleDateFormat Example:

String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);

Will Output:

2018-12-10

Kotlin API Levels 26 or greater, here is a DateTimeFormatter Example:

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("Current Date and Time is: $formatted")
}

Will Output:

Current Date and Time is: 2018-12-10 12:24:36.012