便捷式时间差零 轻松解决时间差问题
背景 项目需要显示发布的内容与当前时间差值
实现 当前时间 1 2 3 4 5 6 7 8 /** * @return 返回当前时间 */ public String getTime() { Date date = new Date(); @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return dateFormat.format(date); }
旧版时间差 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 /** * 返回时间差 * * @param currTime 当前时间 * @param releaseTime 接口获取的时间 * @return */ public String getTimeDifference(String currTime, String releaseTime) throws ParseException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = dateFormat.parse(currTime); Date d2 = dateFormat.parse(releaseTime); 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); String s = days + "天" + hours + "小时" + minutes + "分"; if (days != 0 && hours != 0 && minutes != 0) { return s; } if (days != 0) { if (hours != 0) { if (minutes != 0) { return s; } else { return s.replace(minutes + "分", ""); } } else { s = s.replace(hours + "小时", ""); if (minutes != 0) { return s; } else { return s.replace(minutes + "分", ""); } } } else { s = s.replace(days + "天", ""); if (hours != 0) { if (minutes != 0) { return s; } else { return s.replace(minutes + "分", ""); } } else { s = s.replace(hours + "小时", ""); if (minutes != 0) { return s; } else { return s.replace(minutes + "分", ""); } } } }
新版时间差 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 /** * 返回时间差 * * @param currTime 当前时间 * @param releaseTime 接口获取的时间 * @return */ public String getTimeDifference(String currTime, String releaseTime) throws ParseException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = dateFormat.parse(currTime); Date d2 = dateFormat.parse(releaseTime); 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); String s = days + "天" + hours + "小时" + minutes + "分"; if (days != 0 && hours != 0 && minutes != 0) { return s; } if (days != 0) { return getTime(hours, minutes, s); } else { s = s.replace(days + "天", ""); return getTime(hours, minutes, s); } } private String getTime(long hours, long minutes, String s) { if (hours != 0) { if (minutes != 0) { return s; } else { return s.replace(minutes + "分", ""); } } else { s = s.replace(hours + "小时", ""); if (minutes != 0) { return s; } else { return s.replace(minutes + "分", ""); } } } }
效果 $days+"天"+$hours+"小时"+$minutes+"分"