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

Flutter中TimePicker选24小时制时间却显示为12小时制问题

问题原因分析

你的问题出在_toTime.format(context)这一步:虽然你在showTimePicker的builder里设置了alwaysUse24HourFormat: true,但TimeOfDay.format(context)的输出格式仍受当前上下文全局MediaQuery设置影响,并非一定会返回24小时制字符串。当你选择22:30时,format可能返回"10:30 PM"这类12小时制字符串,此时用DateFormat('HH:mm')解析会默认识别为上午10:30,最终输出错误结果。

解决方案

直接利用TimeOfDay对象自带的hour和minute属性构建24小时制时间字符串,无需通过DateFormat转解析:

TimeOfDay _toTime = TimeOfDay.now();
String closingTime = '';
    
InkWell(
 onTap: () => showTimePicker(
 context: context,
 initialTime: _toTime,
 builder: (context, child) => MediaQuery(
   data: MediaQuery.of(context).copyWith(
   alwaysUse24HourFormat: true),
   child: child ?? Container()))
  .then((value) {
    setState(() {
      if (value != null) {
        _toTime = value;
        // 直接拼接24小时制时间,padLeft保证两位数格式
        closingTime = '${_toTime.hour.toString().padLeft(2, '0')}:${_toTime.minute.toString().padLeft(2, '0')}';
        print('CLOSING TIME: $closingTime');
      }
 });
})
补充说明
  • padLeft(2, '0')用于统一格式,确保小时、分钟均为两位数(比如9点显示为"09",5分钟显示为"05")
  • 增加value != null判断,避免用户取消时间选择时触发空指针异常

内容的提问来源于stack exchange,提问作者coolhack7

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:40:40