Back to Blog

Copilot with Kotlin: Create a list of months in 3 letter format

Sandy LaneSandy Lane

Video: Copilot with Kotlin: Create a list of months in 3 letter format by Taught by Celeste AI - AI Coding Coach

Watch full page →

Copilot with Kotlin: Create a List of Months in 3-Letter Format

In Kotlin, you can easily create a list of month abbreviations using built-in date-time utilities or by defining them manually. This example demonstrates how to generate a list of three-letter month names, which is useful for formatting dates or displaying concise month labels in your applications.

Code

import java.time.Month
import java.time.format.TextStyle
import java.util.Locale

fun main() {
  // Generate a list of months in 3-letter uppercase format using java.time.Month enum
  val months = Month.values()
    .map { it.getDisplayName(TextStyle.SHORT, Locale.ENGLISH).uppercase() }

  println(months)  // Output: [JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC]
}

Key Points

  • Kotlin can leverage Java's java.time.Month enum to access month names easily.
  • The getDisplayName method with TextStyle.SHORT returns the abbreviated month name.
  • Locale.ENGLISH ensures consistent English month abbreviations regardless of system locale.
  • Mapping over Month.values() creates a list of all 12 months in order.
  • Calling uppercase() standardizes the format to uppercase three-letter abbreviations.