Files
plan_flutter/lib/utils/format.dart
zhutao 193d29b0ce 1
2025-09-05 18:00:26 +08:00

53 lines
1.7 KiB
Dart

// /// 格式化日期时间
// String formatDateUS(dynamic date, [String format = 'MM/DD/YYYY hh:mm:ss a']) {
// DateTime dateTime;
//
// if (date is String) {
// dateTime = DateTime.tryParse(date) ?? DateTime.now();
// } else if (date is DateTime) {
// dateTime = date;
// } else {
// dateTime = DateTime.now();
// }
//
// final yyyy = dateTime.year.toString();
// final MM = dateTime.month.toString().padLeft(2, '0');
// final dd = dateTime.day.toString().padLeft(2, '0');
//
// // 12小时制
// final hour12 = (dateTime.hour % 12 == 0 ? 12 : dateTime.hour % 12).toString().padLeft(2, '0');
// final HH = dateTime.hour.toString().padLeft(2, '0'); // 24小时制备用
// final mm = dateTime.minute.toString().padLeft(2, '0');
// final ss = dateTime.second.toString().padLeft(2, '0');
// final ampm = dateTime.hour >= 12 ? 'PM' : 'AM';
//
// String result = format
// .replaceFirst(RegExp('YYYY'), yyyy)
// .replaceFirst(RegExp('MM'), MM)
// .replaceFirst(RegExp('DD'), dd)
// .replaceFirst(RegExp('hh'), hour12)
// .replaceFirst(RegExp('HH'), HH)
// .replaceFirst(RegExp('mm'), mm)
// .replaceFirst(RegExp('ss'), ss)
// .replaceFirst(RegExp('a'), ampm);
//
// return result;
// }
import 'package:intl/intl.dart';
String formatDateUS(String dateStr, {bool withTime = false}) {
// 假设后端返回的格式是 "2025-09-05T15:25:00Z"
final date = DateTime.parse(dateStr);
if (withTime) {
return DateFormat("MMM d, yyyy 'at' h:mm a", 'en_US').format(date.toLocal());
// 输出: Sep 5, 2025 at 11:25 PM (取本地时区)
} else {
return DateFormat("MMM d, yyyy", 'en_US').format(date.toLocal());
// 输出: Sep 5, 2025
}
}