Code Mastery Guides

Your Journey to Mastering Programming Languages: Where Knowledge Meets Code

How to Calculate Age in Kotlin Android

Understanding how to calculate age in Android applications is a fundamental skill for many developers. In this tutorial, we’ll explore a simple and effective way to calculate age using Kotlin programming language in Android.

Prerequisite:

Before we begin, make sure you have the following:

  • Android Studio Installed on your computer,
  • Basic knowledge of Kotlin Programming.

Step 1: Create a new Project:

Launch Android Studio and navigate to File => New => New Project. Select the desired project template, specify your application’s name, opt for Kotlin as the programming language, and click on the ‘Finish’ button to initiate the project creation process.

Step 2: Designing the User Interface:

Design a basic interface to collect the user’s birthdate using an EditText for date input and a button to initiate age calculation.

    
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity2">

    <EditText
        android:id="@+id/et_birth_date"
        android:layout_margin="10dp"
        android:hint="Click to Enter Birth Date"
        android:enabled="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <Button
        android:id="@+id/btn_calculate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Calculate"/>
</LinearLayout>
    

Step 3: Create Date Picker Dialog using Kotlin:

Now, let’s enhance the user experience by implementing a date picker dialog. This dialog will enable users to easily select their birthdate when they click on the EditText. After the user completes the selection, the chosen date will be displayed in the EditText field in the ‘dd/MM/yyyy’ format.

    
        binding.etBirthDate.setOnClickListener {
            val calendar = Calendar.getInstance()
            val datePickerDialog = DatePickerDialog(this,
                { datePicker, year, month, day ->
                    val decimalFormat = DecimalFormat("##")
                    binding.etBirthDate.setText("${decimalFormat.format(day)}
                                                /${decimalFormat.format(month+1)}/$year")
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            )
            datePickerDialog.show()
        }
    

Step 4: Calculate Age

This final step involves initiating the calculation process when the user clicks the ‘Calculate’ button. In this example, the calculated age will be displayed in a Toast message. Feel free to utilize this numerical value as per your specific requirements. We’ll use SimpleDateFormat to format dates and convert strings to Date objects for our calculations.

    
        binding.btnCalculate.setOnClickListener {
            val dateFormat = SimpleDateFormat("dd/MM/yyyy")
            val birthDate = dateFormat.parse(binding.etBirthDate.text.toString())
            val todayDate = Calendar.getInstance().time
            val timeInMillis = birthDate!!.time - todayDate.time

            val ageInSeconds = timeInMillis / 1000
            val ageInMinutes = ageInSeconds / 60
            val ageInHours = ageInMinutes / 60
            val ageInDays = ageInHours / 24
            val ageInYears = (ageInDays / 365).toInt()
            
            Toast.makeText(this, "Your Age is $ageInYears years", Toast.LENGTH_SHORT).show()
            
            //use ageInYears where you needed
        }
    

Click Here to learn more about SimpleDateFormat and other date format techniques.

Step 4: Testing the Application

Run your Android application, select your birthdate, and click ‘Calculate’. The app will then display a Toast message indicating your age in years.

Conclusion:

Congratulations! You’ve successfully implemented age calculation in your Android application using Kotlin. This foundational skill can be expanded upon to create more complex date-related functionalities in your projects. We also use DatePickerDialog to select a date.

Click Here to read more articles about Kotlin Programming.

How to Calculate Age in Kotlin Android

Leave a Reply

Scroll to top