Calculate age from BirthDate

后端 未结 17 1350
攒了一身酷
攒了一身酷 2021-02-07 08:33

I have DatePicker Dialog, When I select date at that time I want to calculate age it\'s working but when I select date of current year at that time it showing the -1 age instead

17条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 08:55

    Now for kotlin Language:

    import java.util.Calendar
    
    
    fun main(args: Array) {
    
    
    print(getAge(yyyy,mm,dd))
    
    }
    
     fun getAge(year: Int, month: Int, day: Int): String {
        val dob = Calendar.getInstance()
        val today = Calendar.getInstance()
    
        dob.set(year, month, day)
    
        var age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR)
    
        if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
            age--
        }
    
        val ageInt = age + 1
    
        return ageInt.toString()
    }
    

提交回复
热议问题