Sling Academy
Home/Kotlin/Calculating Age from Birthdate in Kotlin

Calculating Age from Birthdate in Kotlin

Last updated: December 04, 2024

In this article, we'll explore how to calculate a person's age by using their birthdate in Kotlin, a modern and concise programming language. This is a common task in software applications, especially those related to user profiles or registration forms. Let's dive into some straightforward Kotlin examples to achieve this.

Using Java's LocalDate and ChronoUnit

Kotlin runs on the Java Virtual Machine (JVM), which allows us to utilize Java libraries. For date manipulation, Java's java.time package is quite powerful and can be used in Kotlin, as shown:

import java.time.LocalDate
import java.time.Period

fun calculateAge(birthDate: LocalDate): Int {
    val currentDate = LocalDate.now()
    if (!birthDate.isAfter(currentDate)) {
        return Period.between(birthDate, currentDate).years
    } else {
        throw IllegalArgumentException("Birthdate cannot be in the future")
    }
}

fun main() {
    val birthDate = LocalDate.of(1990, 3, 25)
    println("Age is: ${calculateAge(birthDate)} years")
}

In this example, we use LocalDate to store dates and Period to calculate the difference between the birthDate and the current date. The result gives us the number of years, which is the age.

Checking and Formatting Inputs

Handling incorrect inputs is crucial in programming. Let's add a little error handling and input formatting to our function:

import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException

fun parseAndCalculateAge(birthDateString: String): Int {
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    return try {
        val birthDate = LocalDate.parse(birthDateString, formatter)
        calculateAge(birthDate)
    } catch (e: DateTimeParseException) {
        println("Invalid date format. Please use yyyy-MM-dd.")
        -1
    }
}

In the parseAndCalculateAge function, we used DateTimeFormatter to specify the expected date format and handle parse exceptions to ensure correct input.

Using Kotlin extensions to Simplify Usage

Kotlin's extensions allow for adding functionality to existing classes without modifying their source code. We can create an extension function on the String class for improved usability:

fun String.toAge(): Int {
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    return try {
        val birthDate = LocalDate.parse(this, formatter)
        calculateAge(birthDate)
    } catch (e: DateTimeParseException) {
        println("Invalid date format: $this")
        -1
    }
}

fun main() {
    val birthDateStr = "1990-03-25"
    println("Calculated age: ${birthDateStr.toAge()} years")
}

With this extension function, any string in the correct format can be converted directly to an age calculation using the toAge method.

Conclusion

Calculating age from a birthdate in Kotlin can be seamlessly integrated using Java's powerful time package. By incorporating additional input handling and leveraging Kotlin's extension functions, you can make your age calculation logic both error-proof and flexible. Kotlin provides an intuitive environment to handle such operations efficiently, and learning to utilize its features will empower you to write cleaner and more robust code.

Next Article: How to Get the Current Date and Time in Kotlin

Previous Article: Converting Between `Date` and `LocalDateTime` in Kotlin

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