Display the time. If the difference from the current time is less than one day, it will automatically use ** seconds (minutes, hours) ago. If it is greater than one day, it will display in the format specified by 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; }
You can expand here to meet your specific needs~~
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 } }
Current running: 4 minutes ago
The above is the detailed content of java displays 1 second ago, 1 minute ago, 2 minutes ago, 3 days ago. For more information, please follow other related articles on the PHP Chinese website!