如何从日期选择器中计算年龄?

How do I calculate age from my date picker?

提问人:Shane.B 提问时间:10/26/2022 最后编辑:z.g.yShane.B 更新时间:11/27/2022 访问量:327

问:

我正在自学 Kotlin。我正在尝试在输入出生日期后计算用户的年龄并将其显示在另一个活动中。

我尝试了一堆不同的东西,但没有一个奏效。我敢肯定,我可能忽略了一些简单的事情。

我的代码:


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)
        }


    }}

Android Kotlin DatePicker threetenabp

评论


答:

3赞 z.g.y 10/26/2022 #1

如果您能够使用或至少使用 ThreeTen Android Backport,它应该很容易,如果您使用 .java.timejava.util.Calendar

这是一个您可以轻松复制和粘贴的一小部分工作,这就是我计算两个实例之间年差的方式DatePickerDialogLocalDate

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)

如果我选择并根据此发布的时间对其进行评估,它将打印出来April 1 1995

E/DatePickerTag: Age : 27

但是,如果您不能使用 or ,则此 SO 帖子可能会对您有所帮助。文章的底部包含使用 计算年龄的答案。java.timeThreeTenABPjava.util.Calendar

最后,跑题外话,考虑一下 lateinit var 的用途kotlin null safety 是什么,并避免在代码中不必要地大喊大叫!!

评论

1赞 Shane.B 10/27/2022
用你的方法让它工作。我只需要再合并大约 2 行。感谢您的回应。
1赞 Tumusiime Keith 10/26/2022 #2

内部布局文件

<DatePicker
    android:id="@+id/ageSelectionPicker"
    style="@style/MyDatePicker"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="24dp"
    android:layout_marginTop="16dp"
    android:layout_marginRight="24dp"
    android:backgroundTint="#ff4081"
    android:calendarTextColor="#ff4081"
    android:calendarViewShown="false"
    android:datePickerMode="spinner" />

类.java

DatePicker ageSelectionPicker = findViewById(R.id.ageSelectionPicker);    
int age = getAge(ageSelectionPicker.getYear(), ageSelectionPicker.getMonth(), ageSelectionPicker.getDayOfMonth());

getAge 方法

private int getAge(int year, int month, int day) {
    Calendar dateOfBirth = Calendar.getInstance();
    Calendar today = Calendar.getInstance();

    dateOfBirth.set(year, month, day);

    int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);

    if (today.get(Calendar.DAY_OF_YEAR) < dateOfBirth.get(Calendar.DAY_OF_YEAR)) {
        age--;
    }

    return age;
}