/**
* 輸入一個日期 返回與當前時間做對比的結果 格式如下
* 小於1分鐘:剛剛來過
* 小於1小時:xxx分鐘前來過
* 小於1天:xxx小時前來過
* 小於31天:xxx天前來過
* 小於1年:xxx月前來過
* 大於1年:xxx年前來過
* @param d2 需要與當前時間做比較的時間
* @return
*/
public static String getTimeToStr(Date d2) {
DateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
try {
Date d1 = new Date();
//Date d2 = df.parse(“2019-02-12 11:40:24”);
long diff = d1.getTime() - d2.getTime();//這樣得到的差值是毫秒級別
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
if(days>365){
int years= (int) (days/365);
return years+"年前來過";
}
if(31<days&&days<=365){
int mont= (int) (days/31);
return mont+"月前來過";
}
if(0<days&&days<31){
return days+"天前來過";
}
if(0<hours&&hours<24){
return hours+"小時前來過";
}
if(0<minutes&&minutes<60){
return minutes+"分鐘前來過";
}
return "剛剛來過";
}catch (Exception ex){
ex.printStackTrace();
return "";
}
}
public static String getTimeToStr2(Date d2) {
DateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
try {
Date d1 = new Date();
//Date d2 = df.parse(“2019-02-12 11:40:24”);
long diff = d1.getTime() - d2.getTime();//這樣得到的差值是毫秒級別
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
if(days>365){
int years= (int) (days/365);
return years+"年前更新";
}
if(31<days&&days<=365){
int mont= (int) (days/31);
return mont+"月前更新";
}
if(0<days&&days<31){
return days+"天前更新";
}
if(0<hours&&hours<24){
return hours+"小時前更新";
}
if(0<minutes&&minutes<60){
return minutes+"分鐘前更新";
}
return "剛剛更新";
}catch (Exception ex){
ex.printStackTrace();
return "";
}
}