根据提供的Date计算并转换为常用的日期标签:前天、昨天、凌晨、早上、下午、晚上、明天、后天、15天内等。
public static String getAutoTime(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.set(Calendar.HOUR_OF_DAY, 0);
currentCalendar.set(Calendar.MINUTE, 0);
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
long dateL = calendar.getTimeInMillis();
long nowL = currentCalendar.getTimeInMillis();
if (dateL < nowL - 1296000000L) { // 比15天前还早
if (calendar.get(Calendar.YEAR) == currentCalendar.get(Calendar.YEAR)) { // 在今年
return getDate(date);
} else {
return getDateOneYear(date);
}
} else if (dateL < nowL - 172800000L) { // 比今天0时还早48小时以上
return ((nowL - dateL) / 86400000L) + "天前";
} else if (dateL < nowL - 86400000L) { // 比今天0时还早24小时以上
return "前天 " + getTime(date);
} else if (dateL < nowL) { // 比今天0时还早
return "昨天 " + getTime(date);
} else if (dateL < nowL + 21600000L) { // 今天6点前
return "凌晨 " + getTime(date);
} else if (dateL < nowL + 43200000L) { // 今天12点前
return "早上 " + getTime(date);
} else if (dateL < nowL + 64800000L) { // 今天18点前
return "下午 " + getTime(date);
} else if (dateL < nowL + 86400000L) { // 明天0时前
return "晚上 " + getTime(date);
} else if (dateL < nowL + 172800000L) { // 晚今天0时48小时内
return "明天 " + getTime(date);
} else if (dateL < nowL + 259200000L) { // 晚今天0时72小时内
return "后天 " + getTime(date);
} else {
return getDateOneYear(date);
}
}
格式化日期的方法
public static String getBaseDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:00", Locale.getDefault());
return sdf.format(date);
}
public static String getDateOneYear(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
return sdf.format(date);
}
public static String getDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日", Locale.getDefault());
return sdf.format(date);
}
public static String getTime(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
return sdf.format(date);
}
public static String getWeek(int value) {
switch (value) {
case 1:
return "周日";
case 2:
return "周一";
case 3:
return "周二";
case 4:
return "周三";
case 5:
return "周四";
case 6:
return "周五";
default:
return "周六";
}
}
获取今天昨天前天本周上周上上周时间段:https://blog.csdn.net/Honiler/article/details/89173722