JAVA计算距现在的日期相差年数月数

/**
	 * 计算日期距现在多久前
	 * 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();
	}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值