使用DOM Parser解析此XML Feed:http://loc.grupolusofona.pt/index.php/?format=feed
它工作正常,解析我需要的所有字段,但我想将标记pubDate的结果从“Wed,2012年10月31日17:12:42 +0000”转换为“2天前,在17:12 “或类似的东西。
我该怎么做?
提前致谢。
答案 0 :(得分:2)
以下是您需要的代码:
String dateString = "Wed, 31 Oct 2012 12:12:42 +0100";
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
Date date = null;
try {
date = sdf.parse(dateString);
String timeOfDay = new SimpleDateFormat("HH:mm").format(date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
java.sql.Timestamp timeStampNow = new Timestamp((new java.util.Date()).getTime());
long secondDiff = timeStampNow.getTime() / 1000 - timeStampDate.getTime() / 1000;
int minuteDiff = (int) (secondDiff / 60);
int hourDiff = (int) (secondDiff / 3600);
int dayDiff = daysBetween(date, new Date()) - 1;
if (dayDiff > 0) {
System.out.println("Posted " + dayDiff + " days ago @ " + timeOfDay);
} else if (hourDiff > 0) {
System.out.println("Posted " + hourDiff + " hour(s) ago @ " + timeOfDay);
} else if (minuteDiff > 0) {
System.out.println("Posted " + minuteDiff + " minute(s) ago @ " + timeOfDay);
} else if (secondDiff > 0) {
System.out.println("Posted " + secondDiff + " second(s) ago @ " + timeOfDay);
}
} catch (ParseException e) {
e.printStackTrace();
}
daysBetween:
public static int daysBetween(Date startDate, Date endDate) {
int daysBetween = 0;
while (startDate.before(endDate)) {
startDate.setTime(startDate.getTime() + 86400000);
daysBetween++;
}
return daysBetween;
}
输出: 发表于2天前@ 12:12