时间格式化工具,一秒前,一分钟前,一小时前,昨天,一天前
package com.awifi.cloudnative.container.rbac.user.provider.utils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class dataFormatUtils {
public static String format(Date date) {
// 计算出相差天数
int days = differentDays(date, new Date());
// 同一天
if (0 == days) {
// 计算出时间差
long delta = new Date().getTime() - date.getTime();
// 小于一分钟
if (delta < 1L * 60000L) {
long seconds = toSeconds(delta);
return (seconds <= 0 ? 1 : seconds) + "秒前";
}
// 小于一小时
else if (delta < 1L * 3600000L) {
long minutes = toMinutes(delta);
return (minutes <= 0 ? 1 : minutes) + "分钟前";
}
// 小于24小时
else if (delta < 24L * 3600000L) {
long hours = toHours(delta);
return (hours <= 0 ? 1 : hours) + "小时前";
}
}
// 不同一天
else {
if (1 == days) {
return "昨天";
}
// 几天前
else if (3 >= days) {
return days + "天前";
}
}
// 格式化时间
return getYmdHm(date);
}
private static long toSeconds(long date) {
return date / 1000L;
}
private static long toMinutes(long date) {
return toSeconds(date) / 60L;
}
private static long toHours(long date) {
return toMinutes(date) / 60L;
}
public static String getYmdHm(Date date) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return df.format(date);
}
public static int differentDays(Date oldDate, Date newDate) {
Calendar oldCal = Calendar.getInstance();
oldCal.setTime(oldDate);
Calendar newCal = Calendar.getInstance();
newCal.setTime(newDate);
int oldDay = oldCal.get(Calendar.DAY_OF_YEAR);
int newDay = newCal.get(Calendar.DAY_OF_YEAR);
int oldYear = oldCal.get(Calendar.YEAR);
int newYear = newCal.get(Calendar.YEAR);
// 不是同一年
if (oldYear != newYear) {
int timeDistance = 0;
for (int i = oldYear; i < newYear; i++) {
//如果是闰年
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
timeDistance += 366;
}
//不是闰年
else {
timeDistance += 365;
}
}
return timeDistance + (newDay - oldDay);
}
// 是同一年
else {
return newDay - oldDay;
}
}
}



