在Flutter中如何通过showTimePicker比较选中时间与当前实时时间?
解决TimeOfDay与DateTime的时间对比问题(判断逾期)
核心思路是将用户预先选择的日期和通过showTimePicker获取的TimeOfDay组合成完整的DateTime对象,再与当前实时时间对比,即可判断是否逾期。
实现步骤与代码示例
- 确保已通过日期选择器获取到用户选中的日期(
selectedDate,类型为DateTime) - 调用
showTimePicker获取选中的时间(selectedTime,类型为TimeOfDay) - 合并日期与时间为完整的
DateTime,再和当前时间对比
// 假设已通过日期选择器拿到选中的日期 DateTime selectedDate = DateTime(2024, 5, 20); // 获取用户选中的时间 TimeOfDay? selectedTime = await showTimePicker( context: context, initialTime: TimeOfDay.now(), ); if (selectedTime != null) { // 合并选中的日期和时间为完整的DateTime DateTime selectedDateTime = DateTime( selectedDate.year, selectedDate.month, selectedDate.day, selectedTime.hour, selectedTime.minute, ); // 获取当前实时时间 DateTime currentDateTime = DateTime.now(); // 判断是否逾期:选中时间早于当前时间则为逾期 bool isOverdue = selectedDateTime.isBefore(currentDateTime); }
优化判断逻辑(提升效率)
如果用户选中的是过去的日期,无需对比时分秒可直接判定逾期,避免不必要的计算:
bool isOverdue = false; DateTime currentNow = DateTime.now(); // 获取当天0点的时间,用于判断选中日期是否为今天 DateTime todayStart = DateTime(currentNow.year, currentNow.month, currentNow.day); if (selectedDate.isBefore(todayStart)) { // 选中日期在今天之前,直接判定逾期 isOverdue = true; } else if (selectedDate.isAtSameMomentAs(todayStart)) { // 选中日期是今天,合并时间后对比时分秒 if (selectedTime != null) { DateTime selectedDateTime = DateTime( selectedDate.year, selectedDate.month, selectedDate.day, selectedTime.hour, selectedTime.minute, ); isOverdue = selectedDateTime.isBefore(currentNow); } } else { // 选中日期是未来,不逾期 isOverdue = false; }
内容的提问来源于stack exchange,提问作者Hunter
相关产品推荐
相关产品推荐

