Back to Blog

Kotlin: Create a function to get the last day of the month

Sandy LaneSandy Lane

Video: Kotlin: Create a function to get the last day of the month by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Create a function to get the last day of the month

In Kotlin, you can easily determine the last day of any given month by leveraging the java.time API. This example shows how to write a simple function that returns the last day as an integer for a specified year and month.

Code

import java.time.YearMonth

// Function to get the last day of a given month in a given year
fun getLastDayOfMonth(year: Int, month: Int): Int {
  val yearMonth = YearMonth.of(year, month)  // Create a YearMonth instance
  return yearMonth.lengthOfMonth()           // Returns the last day of the month
}

// Example usage
fun main() {
  val year = 2024
  val month = 2
  println("Last day of $month/$year is ${getLastDayOfMonth(year, month)}")
  // Output: Last day of 2/2024 is 29 (leap year)
}

Key Points

  • The java.time.YearMonth class simplifies working with year-month combinations.
  • The lengthOfMonth() method returns the number of days in the specified month, accounting for leap years.
  • Passing year and month as parameters makes the function reusable for any date.
  • This approach avoids manual calculations and potential errors with month lengths.