import 'package:intl/intl.dart'; extension DateTimeX on DateTime { /// yyyy-MM-dd String get fmtDate => DateFormat('yyyy-MM-dd').format(this); /// yyyy-MM-dd HH:mm:ss String get fmtDateTime => DateFormat('yyyy-MM-dd HH:mm:ss').format(this); /// HH:mm String get fmtHm => DateFormat('HH:mm').format(this); /// 友好相对时间:"刚刚 / 5 分钟前 / 昨天 18:24 / 03-15 / 2024-03-15" String get toFriendly { final now = DateTime.now(); final diff = now.difference(this); if (diff.inSeconds < 60) return '刚刚'; if (diff.inMinutes < 60) return '${diff.inMinutes} 分钟前'; if (diff.inHours < 24 && now.day == day) { return '今天 $fmtHm'; } if (diff.inDays < 2 && now.day - day == 1) { return '昨天 $fmtHm'; } if (year == now.year) { return DateFormat('MM-dd HH:mm').format(this); } return fmtDate; } } extension NullableDateTimeX on DateTime? { String get orPlaceholder => this?.fmtDateTime ?? '-'; String get orPlaceholderDate => this?.fmtDate ?? '-'; }