Sling Academy
Home/Kotlin/Formatting Dates in Kotlin Using `DateTimeFormatter`

Formatting Dates in Kotlin Using `DateTimeFormatter`

Last updated: December 01, 2024

When working with dates and times in Kotlin, especially in formats specific to your application's requirements, DateTimeFormatter class from the Java Time API offers a sophisticated solution. This powerful class allows you to customize the format and parsing of dates and times in a flexible and efficient way.

Getting Started with DateTimeFormatter

Kotlin, being fully interoperable with Java, can leverage the DateTimeFormatter class directly. To format and parse dates, you'll make use of classes like LocalDate, LocalDateTime, and ZonedDateTime.

Importing Required Packages

First, make sure you import the necessary packages:

import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

Formatting Dates

The basic way to format a date in Kotlin using Java’s DateTimeFormatter looks like this:

fun formatLocalDateTime() {
    val currentDateTime = LocalDateTime.now()
    val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss")
    val formattedDate = currentDateTime.format(formatter)
    println("Formatted DateTime: $formattedDate")
}

In this example, we're formatting the current date and time into a string that follows the pattern "dd-MM-yyyy HH:mm:ss", which includes date, hours, minutes, and seconds.

Parsing Dates

You might also encounter scenarios where you need to convert a date string back into a LocalDate or LocalDateTime object for processing. Here’s how you can parse a date string:

fun parseLocalDateTime() {
    val dateString = "31-12-2023 23:59:59"
    val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss")
    val parsedDate = LocalDateTime.parse(dateString, formatter)
    println("Parsed LocalDateTime: $parsedDate")
}

This function takes a string representation of a date, and using the same DateTimeFormatter pattern, it converts that string back to a LocalDateTime object.

Common Patterns

The DateTimeFormatter can be used with a variety of patterns:

  • yyyy-MM-dd - Example: 2023-03-25
  • dd/MM/yyyy - Example: 25/03/2023
  • MMM dd, yyyy - Example: Mar 25, 2023
  • EEEE, MMMM dd, yyyy HH:mm:ss a - Example: Saturday, March 25, 2023 06:30:00 PM

These patterns provide the basis for custom, localized representations of date and time strings and allow applications to handle multiple formats seamlessly.

Handling Custom Date-Time Formats

Often, international applications need to adapt to various specific formats. Consider the scenario where an application requires a format used primarily in a certain locale:

fun customLocaleDateFormat() {
    val currentDate = LocalDate.now()
    val formatter = DateTimeFormatter.ofPattern("eeee, dd MMMM yyyy")
    val formattedDate = currentDate.format(formatter)
    println("Custom Formatted Date: $formattedDate")
}

This code formats the date to display the full day name and month in some locales: "Saturday, 25 March 2023," which is especially useful in specific regional applications.

Conclusion

With Kotlin's seamless support for Java's DateTimeFormatter, handling date and time in a format-aligned manner becomes straightforward. Utilizing various pattern strings, you can effectively cater to multiple locale-specific display requirements and create a robust date-time feature in your app. Spend some time exploring DateTimeFormatter to ensure that your applications support the broad requirements of date and time presentation fully tailored to your developments.

Next Article: Parsing Strings into Dates in Kotlin

Previous Article: Introduction to Kotlin’s `LocalDate`, `LocalTime`, and `LocalDateTime`

Series: Working with date & time in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin