Comparing Timestamps in Java to get difference in days
22,473
Solution 1
Just subtract check_out and check_in, and convert from whatever units you're in to days. Something like
//pseudo-code
diff_in_millis = Absolute Value Of ( check_out - check_in ) ;
diff_in_days = diff_in_millis / (1000 * 60 * 60 * 24);
Solution 2
Following code snippet also will give days difference
private int getDaysBetween (Timestamp start, Timestamp end) {
boolean negative = false;
if (end.before(start)) {
negative = true;
Timestamp temp = start;
start = end;
end = temp;
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(start);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
GregorianCalendar calEnd = new GregorianCalendar();
calEnd.setTime(end);
calEnd.set(Calendar.HOUR_OF_DAY, 0);
calEnd.set(Calendar.MINUTE, 0);
calEnd.set(Calendar.SECOND, 0);
calEnd.set(Calendar.MILLISECOND, 0);
if (cal.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)) {
if (negative)
return (calEnd.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR)) * -1;
return calEnd.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR);
}
int days = 0;
while (calEnd.after(cal)) {
cal.add (Calendar.DAY_OF_YEAR, 1);
days++;
}
if (negative)
return days * -1;
return days;
}
Author by
Daal
Updated on July 23, 2022Comments
-
Daal almost 2 years
I'm retrieving two timestamps from a database (check_in and check_out). I need to compare the two to find out how many days have passed between the two timestamps. How can this be done in Java?