我正在尝试制作一个程序,以找出两个小时之间的差异。 程序在所有小时内搜索到mongoDB的数据库,每次都必须找到它们之间的差异。但是我不知道如何在循环中每次都给出第二个值。
到现在为止,我找到一次并从一个标准中减去。
我每次都可以在循环中搜索前两个时间值。
非常感谢你的帮助!!!
int count = 1;
int start = 1;
while (cursorEvents.hasNext()) {
DBObject documentInEventCollection = cursorEvents.next();
if("pageLoad".equals(documentInEventCollection.get("type"))){
System.out.println("URL(" + count + "): " + documentInEventCollection.get("url").toString());
System.out.println("time-start(" + start + "): " + documentInEventCollection.get("timeStamp").toString());
count++;
start++;
try {
String timeStart = (documentInEventCollection.get("timeStamp").toString());
String timeStop = ("2015-07-24;12:26:54");
SimpleDateFormat format = new SimpleDateFormat("yyyy-dd-MM;HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(timeStart);
d2 = format.parse(timeStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
我使用以下解决方案来计算不同的时间:
//Compute the time diff
Map<TimeUnit, Long> deltaTime = computeDiff(now.getTime(), target.getTime());
//Get the specific values
long d = deltaTime.get(TimeUnit.DAYS);
long m = deltaTime.get(TimeUnit.MINUTES);
long s = deltaTime.get(TimeUnit.SECONDS);
Methode代码:
private static Map<TimeUnit, Long> computeDiff(Date start, Date end) {
long diffMilTime = end.getTime() - start.getTime();
List<TimeUnit> units = new ArrayList<>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit, Long> result = new LinkedHashMap<>();
long restMilTime = diffMilTime;
for (TimeUnit unit : units) {
long diff = unit.convert(restMilTime, TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
restMilTime = restMilTime - diffInMilliesForUnit;
result.put(unit, diff);
}
return result;
}