/**
* 计算日期距现在多久前
* xx年xx月xx天xx小时xx分钟前
* @param date
* @return
*/
public static String calTimeAgo(Date date){
Date nowDate = new Date();
if(date.after(nowDate)){
return "0分钟前";
}
Calendar nowCal = Calendar.getInstance();
nowCal.setTime(nowDate);
Calendar dateCal = Calendar.getInstance();
dateCal.setTime(date);
int yearAgo = nowCal.get(Calendar.YEAR)-dateCal.get(Calendar.YEAR);
int monthAgo = nowCal.get(Calendar.MONTH)-dateCal.get(Calendar.MONTH);
if(monthAgo<0){
yearAgo--;
monthAgo += 12;
}
int dayAgo = nowCal.get(Calendar.DAY_OF_MONTH)-dateCal.get(Calendar.DAY_OF_MONTH);
if(dayAgo<0){
monthAgo--;
dayAgo += dateCal.getActualMaximum(Calendar.DAY_OF_MONTH);
if(monthAgo<0){
yearAgo--;
monthAgo += 12;
}
}
int hourAgo = nowCal.get(Calendar.HOUR_OF_DAY)-dateCal.get(Calendar.HOUR_OF_DAY);
if(hourAgo<0){
dayAgo--;
hourAgo += 24;
if(dayAgo<0){
monthAgo--;
dayAgo += dateCal.getActualMaximum(Calendar.DAY_OF_MONTH);
if(monthAgo<0){
yearAgo--;
monthAgo += 12;
}
}
}
int minuteAgo = nowCal.get(Calendar.MINUTE)-dateCal.get(Calendar.MINUTE);
if(minuteAgo<0){
hourAgo--;
minuteAgo += 60;
if(hourAgo<0){
dayAgo--;
hourAgo += 24;
if(dayAgo<0){
monthAgo--;
dayAgo += dateCal.getActualMaximum(Calendar.DAY_OF_MONTH);
if(monthAgo<0){
yearAgo--;
monthAgo += 12;
}
}
}
}
StringBuilder sb = new StringBuilder();
sb.append(yearAgo<1?"":(yearAgo+"年"))
.append(monthAgo<1?"":(monthAgo+"月"))
.append(dayAgo<1?"":(dayAgo+"天"))
.append(hourAgo<1?"":(hourAgo+"小时"))
.append(minuteAgo<1?"":(minuteAgo+"分钟"))
.append("前");
return sb.toString();
}
JAVA计算距现在的日期相差年数月数
最新推荐文章于 2024-07-26 02:57:26 发布