如何找到kotlin中datepicker之间的区别

how to find the difference between datepicker in kotlin

目前,我的日期选择器对话框有一个开始日期和一个结束日期。我试图找出开始日期和结束日期之间的天数差异。并确保结束日期不会在更早的日期

/* Calendar Start Date Button Click */
        startdatepicker = findViewById(R.id.CalendarStartImage)
        startdateview = findViewById(R.id.StartDateTextView)
        val startCalendar = Calendar.getInstance()

        val startPicker = DatePickerDialog.OnDateSetListener{ view, year, month,dayOfMonth ->
            startCalendar.set(Calendar.YEAR,year)
            startCalendar.set(Calendar.MONTH,month)
            startCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
            updateStartCalendar(startCalendar)
        }

        startdatepicker.setOnClickListener{
            val dialog = DatePickerDialog(this,startPicker, startCalendar.get(Calendar.YEAR), startCalendar.get(Calendar.MONTH), startCalendar.get(Calendar.DAY_OF_MONTH))
//            dialog.datePicker.minDate = startCalendar.getTimeInMillis()
            dialog.datePicker.minDate = (System.currentTimeMillis()-1000)
            dialog.show()
        }
        /* Calendar End Date Button Click */
        enddatepicker = findViewById(R.id.CalendarEndImage)
        enddateview = findViewById(R.id.EndDateTextView)
        val endCalendar = Calendar.getInstance()
        val endPicker = DatePickerDialog.OnDateSetListener{ view, year, month,dayOfMonth ->
            endCalendar.set(Calendar.YEAR,year)
            endCalendar.set(Calendar.MONTH,month)
            endCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
//            DatePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            updateEndCalendar(endCalendar)
        }

        enddatepicker.setOnClickListener{
            val dialog = DatePickerDialog(this,
                endPicker,
                endCalendar.get(Calendar.YEAR),
                endCalendar.get(Calendar.MONTH),
                endCalendar.get(Calendar.DAY_OF_MONTH))
//            dialog.datePicker.minDate = startCalendar.getTimeInMillis()
            dialog.datePicker.minDate = (System.currentTimeMillis()-1000)
            dialog.show()
        }

    }
    private fun updateStartCalendar(startCalendar: Calendar){
        val myformat = "MM-dd-yyyy"
        val mydateformat = SimpleDateFormat(myformat,Locale.ENGLISH)
        startdateview.text=(mydateformat.format(startCalendar.time))
    }
    private fun updateEndCalendar(endCalendar: Calendar){
        val myformat = "MM-dd-yyyy"
        val mydateformat = SimpleDateFormat(myformat,Locale.ENGLISH)
        Log.d("check", endCalendar.time.toString())
        enddateview.text=(mydateformat.format(endCalendar.time))
    }

要检查两个日历日期之间的时差,您可以使用:

val duration = Duration.between(startCalendar, endCalendar)
val durationDays = duration.inWholeDays()

您还可以使用以下方法检查它是否为负数:

if(duration.isNegative){
    //do something
} else{
    //do something else
}