format static method
String
format(
- int millisecondsSinceEpoch, {
- bool dayOnly = true,
})
Implementation
static String format(int millisecondsSinceEpoch, {bool dayOnly = true}) {
// 当天日期
DateTime nowDate = DateTime.now();
// 传入日期
DateTime targetData =
DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch);
String prefix = "";
// 是否当年
if (nowDate.year != targetData.year) {
prefix = DateFormat('yyyy年M月d日').format(targetData);
} else if (nowDate.month != targetData.month) {
// 同一年 不同月份
prefix = DateFormat('M月d日').format(targetData);
} else if (nowDate.day != targetData.day) {
//同一月 不同天
if (nowDate.day - targetData.day == 1) {
prefix = '昨天';
} else {
prefix = DateFormat('M月d日').format(targetData);
}
}
if (prefix.isNotEmpty && dayOnly) {
return prefix;
}
int targetHour = targetData.hour;
String returnTime = "", suffix = DateFormat('h:mm').format(targetData);
if (targetHour >= 0 && targetHour < 6) {
returnTime = '凌晨';
} else if (targetHour >= 6 && targetHour < 8) {
returnTime = '早晨';
} else if (targetHour >= 8 && targetHour < 11) {
returnTime = '上午';
} else if (targetHour >= 11 && targetHour < 13) {
returnTime = '中午';
} else if (targetHour >= 13 && targetHour < 18) {
returnTime = '下午';
} else if (targetHour >= 18 && targetHour <= 23) {
returnTime = '晚上';
}
if (prefix.isEmpty) {
return '$returnTime$suffix';
} else {
return '$prefix $returnTime$suffix';
}
}