class revrsetime {
public static void main(String[] args) {
System.out.println(setLastSeenTime("26/08/2014 14:29:00"));
}
public static String setLastSeenTime(String time) {
long milliseconds = Math.abs(System.currentTimeMillis()
- converTimeStringINToMillis(time));
String lastSeen = "";
long seconds = (long) milliseconds / 1000;
if (seconds < 60)
lastSeen = String.valueOf(seconds) + "sec ago";
else if (seconds > 60 && seconds < 3600)
lastSeen = String.valueOf((int) seconds / 60) + " min ago";
else if (seconds > 3600 && seconds < 86400)
lastSeen = String.valueOf((int) seconds / 3600) + " hours ago";
else if (seconds > 86400 && seconds < 172800)
lastSeen = " Yesterday";
else if (seconds > 172800 && seconds < 2592000)
lastSeen = String.valueOf((int) (seconds / (24 * 3600)))
+ " days ago";
else if (seconds > 2592000)
lastSeen = String.valueOf((int) (seconds / (30 * 24 * 3600)))
+ " months ago";
return lastSeen;
}
private static long converTimeStringINToMillis(String time) {
long milliseconds = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// 25/06/2014 8:41:26
Date date;
date = sdf.parse(time);
milliseconds = date.getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
milliseconds = 0;
e.printStackTrace();
}
return milliseconds;
}
}
这是我的代码,用于显示Lastseendate和时间,我正在做什么,我从Web服务和系统时间得到时间使它有所不同。在某些情况下,我得到正确的输出,但在其他情况下,我不是。
我设置日期和时间时的输出:26/08/2014 13:29:00然后它显示3小时前它应该显示2小时前。当我设置26/08/2014 14:29:00然后它显示4小时前。
我不知道我犯了哪个错误,请帮忙。
答案 0 :(得分:3)
sdf.setTimeZone(TimeZone.getTimeZone( “UTC”));在Code中删除它会正常工作。