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

Dart相对时间格式化函数返回0 months ago异常问题排查

错误原因及修复方案

核心触发问题

你在月份判断分支中存在笔误:进入(difference.inDays / 30).floor() >= 2分支的前提是已经通过了上层「不足1年」的判断,你在拼接返回值时错误使用了(difference.inDays / 365).floor()计算月份数值,该计算结果必然为0,所以会固定返回0 months ago。
将该分支的除数365替换为30即可修复,修正后代码:

else if ((difference.inDays / 30).floor() >= 2) {
  return "hace".tr()+'${(difference.inDays / 30).floor()}'+"monthsago".tr();
}

其余隐藏错误

你在1年判断分支中多余拼接了(numericDates).toString(),会导致非数字日期模式下输出异常内容,需要删除多余拼接逻辑:

// 修正前
else if ((difference.inDays / 365).floor() >= 1  ) {
  return (numericDates) ? '1yearago'.tr() : 'lastyear'.tr()+" "+(numericDates).toString();
}
// 修正后
else if ((difference.inDays / 365).floor() >= 1  ) {
  return (numericDates) ? '1yearago'.tr() : 'lastyear'.tr();
}

优化建议

直接用difference.inDays除以30/365计算年月间隔存在误差(比如2月仅有28天、闰年情况),如果需要更高精度,可以直接对比两个DateTime对象的年、月字段差值计算间隔。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:30:01