我有一个ISO-8601格式的日期/时间字符串,如:2011-04-15T20:08:18Z
我想将其格式化为更易读的日期/时间,然后还可以将其与手机当地时间进行比较。我对被弃用的东西和没有被弃用的东西感到有点困惑。
我需要使用Calendar
对象吗?
有人可以告诉我如何做到这一点吗?
答案 0 :(得分:7)
以下是您可以使用的代码段
StringBuffer sbDate = new StringBuffer();
sbDate.append(cDate);
String newDate = sbDate.substring(0, 19).toString();
String rDate = newDate.replace("T", " ");
String nDate = rDate.replaceAll("-", "/");
nDate 会以正常格式给你日期,比较两个日期继续像
long epoch = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(nDate).getTime();
Date currentDate = new Date();
long diffInSeconds = (currentDate.getTime() - epoch) / 1000;
String elapsed = "";
long seconds = diffInSeconds;
long mins = diffInSeconds / 60;
long hours = diffInSeconds / 3600;
long days = diffInSeconds / 86400;
long weeks = diffInSeconds / 604800;
long months = diffInSeconds / 2592000;
if (seconds < 120) {
elapsed = "a min ago";
} else if (mins < 60) {
elapsed = mins + " mins ago";
} else if (hours < 24) {
elapsed = hours + " "+ (hours > 1 ? "hrs" : "hr")+ " ago";
} else if (hours < 48) {
elapsed = "a day ago";
} else if (days < 7) {
elapsed = days + " days ago";
} else if (weeks < 5) {
elapsed = weeks + " " + (weeks > 1 ? "weeks" : "week") + " ago";
} else if (months < 12) {
elapsed = months" " + (months > 1 ? "months" : "months")+ " ago";
} else {
elapsed = "more than a year ago";
}
通过这种方式,您将能够以适当的格式获取日期,并且您将能够比较日期并获得年,月,周,日,小时,分钟或秒的差异。