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

设置每日重复任务时触发FormatException错误,寻求技术帮助

问题根源

你遇到的FormatException是时间格式不匹配导致的:

  • DateFormat.jm()用于解析带AM/PM标识的12小时制时间(比如"02:38 AM")
  • 但你的task.startTime是不带AM/PM的24小时制时间字符串(比如"02:38")
    解析器尝试读取第6位字符时,输入字符串只有5个字符,因此抛出Trying to read from 02:38 at position 6的错误。
解决方案

根据你的场景,有两种简洁的修复方式:

方式1:用对应格式解析

既然task.startTime是HH:mm格式,直接用DateFormat('HH:mm')解析后提取时分:

if (task.repeat == 'Daily') {
    DateTime date = DateFormat('HH:mm').parse(task.startTime.toString());
    notifyHelper.scheduledNotification(date.hour, date.minute, task);
}

方式2:直接拆分字符串(更高效)

如果能确定task.startTime始终是HH:mm格式,也可以跳过DateFormat,直接拆分字符串获取时分:

if (task.repeat == 'Daily') {
    final timeParts = task.startTime.toString().split(':');
    final hours = int.parse(timeParts[0]);
    final minutes = int.parse(timeParts[1]);
    notifyHelper.scheduledNotification(hours, minutes, task);
}

注意事项

处理时间解析时,务必保证解析格式和输入字符串的格式严格对应:

  • 12小时制带AM/PM标识:用DateFormat.jm()或DateFormat('h:mm a')
  • 24小时制无额外标识:用DateFormat('HH:mm')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:55:21