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

如何在Flutter中实现未来活动日期倒计时并计算剩余时间

日期倒计时功能实现(Dart)

现有代码问题

你当前的实现仅计算了两个日期的总天数差值,没有拆分月、日维度,且没有处理日期合法性、过期时间等边界场景,因此无法输出符合要求的「剩余X个月X天」格式结果。

修复后实现代码

static String? dateDiff(String targetDateStr) {
  // 校验输入合法性
  if (targetDateStr == "null" || targetDateStr.isEmpty) return null;
  try {
    final DateTime nowUtc = DateTime.now().toUtc();
    final DateTime targetUtc = DateTime.parse(targetDateStr).toUtc();

    // 处理目标时间已过期的情况
    if (targetUtc.isBefore(nowUtc)) {
      return "活动已结束";
    }

    int years = targetUtc.year - nowUtc.year;
    int months = targetUtc.month - nowUtc.month;
    int days = targetUtc.day - nowUtc.day;

    // 处理天数为负的情况,借1个月换算
    if (days < 0) {
      months -= 1;
      // 计算上个月的总天数
      final prevMonth = DateTime(targetUtc.year, targetUtc.month, 0);
      days += prevMonth.day;
    }

    // 处理月数为负的情况,借1年换算
    if (months < 0) {
      years -= 1;
      months += 12;
    }

    // 拼接输出格式
    List<String> parts = [];
    if (years > 0) parts.add("${years}年");
    if (months > 0) parts.add("${months}个月");
    if (days > 0) parts.add("${days}天");
    // 处理目标日期为当天的场景
    if (parts.isEmpty) {
      return "活动今日开始";
    }
    return "剩余${parts.join('')}";
  } catch (e) {
    // 日期解析失败容错处理
    return null;
  }
}

效果示例

假设当前UTC时间为2024-09-16 00:00:00.000Z,传入目标日期2024-10-18 17:00:00.000Z,输出结果为:剩余1个月2天

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:06:02