Search code examples
androidkotlindatepickerthreetenabp

How do I calculate age from my date picker?


I am learning Kotlin on my own. I am trying to calculate the age of a user after the have input their date of Birth and display it in another activity.

I tried a bunch of different stuff and none worked. I'm sure I maybe overlooking something simple.

my code:


class MainActivity : AppCompatActivity() {
    var date1: EditText? = null
    var datePickerDialog: DatePickerDialog? = null
    lateinit var submitButton: Button
    lateinit var userInput: EditText
    lateinit var dob: EditText
    @SuppressLint("SetTextI18n", "MissingInflatedId", "CutPasteId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(layout.activity_main)
        date1 = findViewById<EditText>(id.date) as EditTe
        date1!!.setOnClickListener{ // calender class's instance and get current date , month and year from calender
            val c = Calendar.getInstance()
            val mYear = c[Calendar.YEAR] // current year
            val mMonth = c[Calendar.MONTH] // current month
            val mDay = c[Calendar.DAY_OF_MONTH] // current day
            datePickerDialog = DatePickerDialog(
                this@MainActivity,
                { view, year, monthOfYear, dayOfMonth -> // set day of month , month and year value in the edit text
                    date1!!.setText(
                        dayOfMonth.toString() + "/"
                                + (monthOfYear + 1) + "/" + year
                    )
                }, mYear, mMonth, mDay

            )
            datePickerDialog!!.show()

        }

        submitButton = findViewById(id.sub_btn)
        userInput = findViewById(id.username1)
        dob = findViewById(id.date)

        submitButton.setOnClickListener {
            val age= dob.text.toString()
            val name= userInput.text.toString()
            //val str = userInput.text.toString()
            intent = Intent(this, CardReturn::class.java)
            intent.putExtra("message_key","Name:$name")
            intent.putExtra("message_key1","DOB:$age")
            startActivity(intent)
        }


    }}


Solution

  • If you're able to utilize java.time or at least ThreeTen Android Backport, it should be easy and will save you from a lot of work if your'e using java.util.Calendar.

    Here's a small working piece of DatePickerDialog that you can copy and paste easily, this is how I calculate year difference between two LocalDate instance

    val now = LocalDateTime.now()
    val initYear = now.year
    val initMonth = now.monthValue - 1 // offset it -1 because January starts at 0 index
    val initDay = now.dayOfMonth
    
    val datePickerDialog = DatePickerDialog(
           this@ActivityOrContext, 
           { _: DatePicker, pickedYear: Int, pickedMonth: Int, pickedDay: Int ->
    
                val selectedBirthdate = LocalDate.of(pickedYear, pickedMonth + 1, pickedDay)
                val age = Period.between(selectedBirthdate, LocalDate.now()).years
    
                Log.e("DatePickerTag", "Age : $age")
    
           }, initYear, initMonth, initDay)
    

    If I select April 1 1995 and evaluate it against the time of this posting it will print

    E/DatePickerTag: Age : 27
    

    If however you can't use java.time or ThreeTenABP, this S.O post might help you otherwise. The bottom section of the post contains answers for calculating age using java.util.Calendar.

    Lastly, out-of-topic, consider what lateinit var is for, what kotlin null safety is, and avoid shouting in your code unnecessarily!!