import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author Guo ZhiShun
* @className DateUtil
* @create 2020/10/30 08:48
* @description
**/
public class DateUtil {
/**
* 获取和当前时间差值,并转换成年月天周时分前
* @param date 计算的时间
* @return 多久前
*/
public static String conversionDate(Date date){
long currentTimeMillis = System.currentTimeMillis();
long oldTimeMillis = date.getTime();
long difference = currentTimeMillis - oldTimeMillis;
String result = "";
long minute = 60 * 1000;
long hour = 60 * minute;
long day = 24 * hour;
long week = 7 * day;
long month = 30 * day;
long year = 365 * day;
int _year = (int)(difference / year);
int _month = (int)(difference / month);
int _week = (int)(difference / week);
int _day = (int)(difference / day);
int _hour = (int)(difference / hour);
int _minute = (int)(difference / minute);
if(_year >= 1){
result = "发表于"+_year+ "年前";
} else if(_month >= 1){
result = "发表于"+_month+ "月前";
} else if(_week >= 1){
result = "发表于"+_week+ "周前";
} else if(_day >= 1){
result = "发表于"+_day+ "天前";
} else if(_hour >= 1){
result = "发表于"+_hour+ "小时前";
} else if (_minute >= 1) {
result = "发表于"+_minute+ "分钟前";
} else {
result = "刚发表";
}
return result;
}
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2020-10-30 09:15:15");
System.out.println(conversionDate(date));
}
}
06-05
977
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)