Back to Blog

Kotlin with Copilot: Test to see how many days there are in this month

Sandy LaneSandy Lane

Video: Kotlin with Copilot: Test to see how many days there are in this month by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin with Copilot: Test to See How Many Days There Are in This Month

In this example, we use Kotlin's standard library to determine the number of days in the current month. By leveraging the java.time API, we can easily get the current date and calculate the length of the month dynamically, which is useful for date-related logic in your applications.

Code

import java.time.LocalDate

fun main() {
  // Get the current date
  val today = LocalDate.now()

  // Get the number of days in the current month
  val daysInMonth = today.lengthOfMonth()

  println("Number of days in this month: $daysInMonth")
}

Key Points

  • Use LocalDate.now() to obtain the current date in Kotlin.
  • The lengthOfMonth() function returns the number of days in the month of the LocalDate instance.
  • This approach automatically accounts for leap years and varying month lengths.
  • The java.time API is the modern, recommended way to work with dates in Kotlin.