You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:21:03