如何将“20170712T18:43:04.000Z”转换为安卓或java中的相对时间? 4 月,2 周 Questions & Answers 559 如何将“2017-07-12T18:43:04.000Z”转换为1小时前或1周前的ago格式
# 1 楼答案 必须通过SimpleDateFormat将dtStart字符串转换为日期对象。 之后,你可以用date.getTime()方法在毫秒内得到它,并计算它与当前时间的差。现在,通过这一差异,你可以得到你想要的ago格式: public String getDate(String dtStart) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { Date date = format.parse(dtStart); long diff = System.currentTimeMillis() - date.getTime(); long hours = Math.round(diff / (60 * 60 * 1000)); if(hours < 24) { return hours + " hours ago"; } else { long days = Math.round(diff / (24.0 * 60 * 60 * 1000)); if (days == 0) return "today"; else if (days == 1) return "yesterday"; else if (days < 14) return days + " days ago"; else if (days < 30) return ((int) (days / 7)) + " weeks ago"; else if (days < 365) return ((int) (days / 30)) + " months ago"; else return ((int) (days / 365)) + " years ago"; } } catch (ParseException e) { e.printStackTrace(); } return ""; }
# 1 楼答案
必须通过
SimpleDateFormat
将dtStart
字符串转换为日期对象。 之后,你可以用date.getTime()
方法在毫秒内得到它,并计算它与当前时间的差。现在,通过这一差异,你可以得到你想要的ago格式: