下面的代码运行良好,我试图确定一旦选择日期后如何计算总天数。非常感谢。
我要解决的问题: 选择休假开始日期-日期选择器-这部分效果很好 选择假期结束日期-日期选择器-这部分效果很好 总天数=计算结束日期-开始日期-我不知道如何进行计算 总共10天
这是我的代码
class VacationActivity : AppCompatActivity() {
private var selectedYear = 0
private var selectedMonth = 0
private var selectedDay = 0
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_vacation)
// get view
val tvDate = findViewById<TextView>(R.id.from_date_view)
tvDate.setOnClickListener {
val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)
if (tvDate.text.isNotEmpty()) {
this.selectedYear
this.selectedMonth
this.selectedDay
}
var listener = DatePickerDialog.OnDateSetListener { view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay
tvDate.text = "${selectedMonth + 1}/$selectedDay/$selectedYear"
}
val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()
}
val tvDate2 = findViewById<TextView>(R.id.to_date_view)
tvDate2.setOnClickListener {
val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)
if (tvDate2.text.isNotEmpty()) {
this.selectedYear
this.selectedMonth
this.selectedDay
}
var listener = DatePickerDialog.OnDateSetListener { view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay
tvDate2.text = "${selectedMonth + 1}/$selectedDay/$selectedYear"
}
val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()
}
}
}
答案 0 :(得分:1)
您可以使用以下功能:
fun getLocalDateFromString(d: String, format: String): LocalDate {
return LocalDate.parse(d, DateTimeFormatter.ofPattern(format))
}
它从以LocalDate
格式设置的字符串d
返回format
。
fun getDaysDif(fromDate: LocalDate, toDate: LocalDate): Long {
return ChronoUnit.DAYS.between(fromDate, toDate)
}
它返回两个日期(LocalDate
)之间的天数差异
因此您可以这样做:
val days = getDaysDif(
getLocalDateFromString(tvDate1.text, "MM/dd/yyyy"),
getLocalDateFromString(tvDate2.text, "MM/dd/yyyy"))
以上代码适用于API级别26及更高版本。
对于较低版本,请使用此:
val format = SimpleDateFormat("MM/dd/yyyy")
val days = TimeUnit.DAYS.convert(
format.parse(tvDate2.text).getTime() -
format.parse(tvDate1.text).getTime(),
TimeUnit.MILLISECONDS)