Files
2026-09-21 17:37:53 +08:00

69 lines
2.6 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'package:intl/intl.dart';
/// billDate 标准格式 yyyy-MM-dd
String formatDate(DateTime date) => DateFormat('yyyy-MM-dd').format(date);
/// 解析后端日期字段,兼容 yyyy-MM-dd 与 yyyy-MM-ddTHH:mm:ss(LocalDateTime)两种格式
String parseBillDate(String? raw) {
if (raw == null || raw.isEmpty) return formatDate(DateTime.now());
final tIndex = raw.indexOf('T');
if (tIndex > 0) return raw.substring(0, tIndex);
final spaceIndex = raw.indexOf(' ');
if (spaceIndex > 0) return raw.substring(0, spaceIndex);
return raw;
}
/// 解析后端日期为 DateTime,失败返回 null
DateTime? tryParseDate(String? raw) {
if (raw == null || raw.isEmpty) return null;
return DateTime.tryParse(raw);
}
// ---------------- 月份 / 周 相关(首页、统计页用) ----------------
/// 当月 1 日 00:00,作为月份锚点使用
DateTime monthStart(DateTime date) => DateTime(date.year, date.month, 1);
/// 当月最后一天 00:00。
/// 用 day = 0 让 DateTime 自动回退到上个月最后一天,避免手算 28/30/31。
DateTime monthEnd(DateTime date) => DateTime(date.year, date.month + 1, 0);
/// 月份平移(delta 为月数,可为负),跨年由 DateTime 自动归一
DateTime shiftMonth(DateTime month, int delta) =>
DateTime(month.year, month.month + delta, 1);
/// 本周一 00:00(以周一为一周起点,对齐 uniApp 的 getWeekStart)
DateTime weekStart(DateTime date) {
final d = DateTime(date.year, date.month, date.day);
return d.subtract(Duration(days: d.weekday - DateTime.monday));
}
/// 是否为同一个自然月
bool isSameMonth(DateTime a, DateTime b) => a.year == b.year && a.month == b.month;
/// 月份标题:2026年9月
String formatMonthTitle(DateTime month) => '${month.year}年${month.month}月';
const List<String> _weekdayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
/// 分组头日期:今天 / 昨天 / 09-21 周一
///
/// 注意:不要用 DateFormat('EEEE', 'zh_CN')——本项目未调用
/// initializeDateFormatting,会抛 LocaleDataException,所以手写星期名。
String formatGroupDate(String billDate) {
final parsed = tryParseDate(billDate);
if (parsed == null) return billDate;
final today = DateTime.now();
final todayStart = DateTime(today.year, today.month, today.day);
final target = DateTime(parsed.year, parsed.month, parsed.day);
final diff = todayStart.difference(target).inDays;
if (diff == 0) return '今天';
if (diff == 1) return '昨天';
final mm = target.month.toString().padLeft(2, '0');
final dd = target.day.toString().padLeft(2, '0');
return '$mm-$dd ${_weekdayNames[target.weekday - 1]}';
}