Flutter中使用DatePicker选择endDate时如何默认设置时间为11:59 PM?
解决方案
实现逻辑如下:
- Flutter 自带的
showDatePicker组件仅返回选中日期的年月日字段,默认携带的时间为当日00:00:00,你只需要在拿到结束日期的选中结果后,手动拼接23时59分的时间参数即可。 - 结束日期的格式化规则需要和开始日期保持一致,使用带12小时制时间的格式串,才能输出你需要的
11:59 PM效果。
修改后的参考代码如下:
static DateTime nope = DateTime.now(); var selectedStartDate = DateFormat('dd/MM/yyyy hh:mm a'); Future<Null> _selectDate(BuildContext context) async { final DateTime picked = await showDatePicker( context: context, initialDate: nope, firstDate: DateTime(2000, 8), lastDate: DateTime(2101)); if (picked != null && picked != nope) setState(() { // 开始日期默认取00:00:00即可,直接赋值 nope = DateTime(picked.year, picked.month, picked.day, 0, 0); }); startDate.text = selectedStartDate.format(nope); } static DateTime yep = DateTime.now(); // 修改结束日期的格式化规则,带上12小时制时间参数 var selectEndDate = DateFormat('dd/MM/yyyy hh:mm a'); Future<Null> _selecteddate(BuildContext context) async { final DateTime pick = await showDatePicker( context: context, initialDate: yep, firstDate: DateTime(2000, 8), lastDate: DateTime(2101)); if (pick != null && pick != yep) setState(() { // 手动给结束日期设置23时59分,格式化后自动转为11:59 PM yep = DateTime(pick.year, pick.month, pick.day, 23, 59); }); endDate.text = selectEndDate.format(yep); }
如果需要更严谨的结束时间边界,也可以把秒和毫秒也设置为最大值:yep = DateTime(pick.year, pick.month, pick.day, 23, 59, 59, 999);
内容的提问来源于stack exchange,提问作者Spsnamta
相关产品推荐
相关产品推荐

