Comparing Timestamps in Java to get difference in days [duplicate]
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?
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);
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;
}
I sort my Set myClassSet by date do as follows:
private Set<MyClass> orderLocation(Set<MyClass> myClassSet) {
List<MyClass> elementList = new ArrayList<MyClass>();
elementList.addAll(myClassSet);
// Order by date
Collections.sort(elementList, this.comparatorElements);
Set<MyClass> l = new TreeSet<MyClass>(comparatorElements);
l.addAll(elementList);
return l;
}
private final Comparator<MyClass> comparatorElements = new Comparator<MyClass>() {
@Override
public int compare(MyClass element1, MyClass element2) {
long l1 = element1.getDate().getTime();
long l2 = element2.getDate().getTime();
if (l2 > l1)
return 1;
else if (l1 > l2)
return -1;
else
return 0;
}
};
int frequency=0;
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse("2014-11-01 04:04:51.451975");
cal1.setTime(date);
date = sdf.parse("2015-11-30 04:04:51.451975");
cal2.setTime(date);
Date d1,d2;
d1=cal1.getTime();
d2=cal2.getTime();
frequency =(int)(TimeUnit.DAYS.convert(d2.getTime() - d1.getTime(), TimeUnit.MILLISECONDS));
System.out.println ("Days: " + frequency);
精彩评论