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

Dart/Flutter实现日期转今日/昨日格式 代码优化咨询

日期显示优化:“今日/昨日”替代具体日期的实现方案

你的这段代码是可行的,能够正确识别今日、昨日并输出对应文本,其他日期也能按照MMMEd格式正常展示。不过代码确实存在冗余和可优化的空间,下面给出几种进阶实现方式:

基础优化版:精简逻辑,修复时分秒判断问题

原代码中如果目标日期的时分秒和当前时间不同(比如目标是今日0点,当前是今日10点),会误判为非今日。优化后只对比日期部分,同时精简逻辑:

import 'package:intl/intl.dart';

String getDateAsString(DateTime date) {
  final now = DateTime.now();
  // 构造仅包含年月日的今日、昨日对象,忽略时分秒
  final today = DateTime(now.year, now.month, now.day);
  final yesterday = today.subtract(const Duration(days: 1));
  final targetDate = DateTime(date.year, date.month, date.day);

  if (targetDate.isAtSameMomentAs(today)) {
    return '今日';
  } else if (targetDate.isAtSameMomentAs(yesterday)) {
    return '昨日';
  } else {
    return DateFormat.MMMEd().format(date);
  }
}

void main() {
  DateTime date = DateTime(2023, 08, 12);
  print(getDateAsString(date));
}

优化点说明

  • 仅获取一次当前时间now,避免重复调用DateTime.now()造成冗余
  • 构造日期对象时忽略时分秒,确保日期判断的准确性
  • 用isAtSameMomentAs替代手动对比年月日,代码更简洁
  • 扁平化if-else结构,提升可读性

进阶扩展版:封装为DateTime扩展方法

将功能封装为DateTime的扩展方法,让调用更直观:

import 'package:intl/intl.dart';

extension DateTimeRelativeFormatter on DateTime {
  String toRelativeDateString() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));
    final targetDate = DateTime(year, month, day);

    if (targetDate.isAtSameMomentAs(today)) {
      return '今日';
    } else if (targetDate.isAtSameMomentAs(yesterday)) {
      return '昨日';
    } else {
      return DateFormat.MMMEd().format(this);
    }
  }
}

// 调用示例
void main() {
  DateTime date = DateTime(2023, 08, 12);
  print(date.toRelativeDateString()); // 输出对应格式
}

额外优化建议

  • 多语言支持:如果应用需要适配多语言,可使用intl包的本地化字符串,替换硬编码的“今日”“昨日”,比如通过AppLocalizations.of(context)!.today获取对应语言文本
  • 时区处理:如果涉及UTC时间,可将DateTime.now()替换为DateTime.now().toUtc(),确保日期判断的时区一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:57:51