java顯示1秒前,1分鐘前,2分鐘前,3天前
阿新 • • 發佈:2019-01-24
/** * 顯示時間,如果與當前時間差別小於一天,則自動用**秒(分,小時)前,如果大於一天則用format規定的格式顯示 * * @author wxy * @param ctime * 時間 * @param format * 格式 格式描述:例如:yyyy-MM-dd yyyy-MM-dd HH:mm:ss * @return */ public static String showTime(Date ctime, String format) { //System.out.println("當前時間是:"+new Timestamp(System.currentTimeMillis())); //System.out.println("釋出時間是:"+df.format(ctime).toString()); String r = ""; if(ctime==null)return r; if(format==null)format="MM-dd HH:mm"; long nowtimelong = System.currentTimeMillis(); long ctimelong = ctime.getTime(); long result = Math.abs(nowtimelong - ctimelong); if(result < 60000){// 一分鐘內 long seconds = result / 1000; if(seconds == 0){ r = "剛剛"; }else{ r = seconds + "秒前"; } }else if (result >= 60000 && result < 3600000){// 一小時內 long seconds = result / 60000; r = seconds + "分鐘前"; }else if (result >= 3600000 && result < 86400000){// 一天內 long seconds = result / 3600000; r = seconds + "小時前"; }else if (result >= 86400000 && result < 1702967296){// 三十天內 long seconds = result / 86400000; r = seconds + "天前"; }else{// 日期格式 format="MM-dd HH:mm"; SimpleDateFormat df = new SimpleDateFormat(format); r = df.format(ctime).toString(); } return r; }
這裡可以更具自己具體的需求進行擴充套件~~
public static void main(String[] args) {
try{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(showTime(df.parse("2015-02-27 11:31:00"),"yyyy-MM-dd HH:mm:ss"));
}catch (Exception e) {
// TODO: handle exception
}
}
當前執行:4分鐘前