49 lines
1.3 KiB
Dart
49 lines
1.3 KiB
Dart
class DateFormatter {
|
|
/// 格式化日期显示
|
|
static String formatDate(DateTime date) {
|
|
final now = DateTime.now();
|
|
final today = DateTime(now.year, now.month, now.day);
|
|
final dateToCheck = DateTime(date.year, date.month, date.day);
|
|
final difference = today.difference(dateToCheck).inDays;
|
|
|
|
// 格式化日期部分
|
|
String dateStr;
|
|
if (date.year == now.year) {
|
|
// 当年日期显示 月-日
|
|
dateStr = '${_padZero(date.month)}-${_padZero(date.day)}';
|
|
} else {
|
|
// 非当年日期显示 年-月-日
|
|
dateStr = '${date.year}-${_padZero(date.month)}-${_padZero(date.day)}';
|
|
}
|
|
|
|
// 获取提示文案
|
|
String hint;
|
|
switch (difference) {
|
|
case 0:
|
|
hint = '今天';
|
|
break;
|
|
case 1:
|
|
hint = '昨天';
|
|
break;
|
|
case 2:
|
|
hint = '前天';
|
|
break;
|
|
default:
|
|
// 获取星期几
|
|
hint = _getWeekDay(date);
|
|
}
|
|
|
|
return '$dateStr $hint';
|
|
}
|
|
|
|
/// 数字补零
|
|
static String _padZero(int number) {
|
|
return number.toString().padLeft(2, '0');
|
|
}
|
|
|
|
/// 获取星期几
|
|
static String _getWeekDay(DateTime date) {
|
|
final weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
|
return weekDays[date.weekday % 7];
|
|
}
|
|
} |