2010-08-17 103 views

回答

5

只需减去check_out和check_in,然后将您所处的任何单位转换为天数。像

//pseudo-code 
diff_in_millis = Absolute Value Of (check_out - check_in) ; 
diff_in_days = diff_in_millis/(1000 * 60 * 60 * 24); 
+0

这给了我一些头痛如果两个时间戳来自不同的主机。每日边界(12:00)的几毫米差异可能会导致不同的值。 – yottamoto 2013-02-05 12:35:20

2

下面的代码片段也将给天差

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; 
    } 
0

我整理我的设定日期myClassSet东西做如下:

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; 
    } 
}; 
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); 
+0

这可能并不总是符合您的期望,因为它会截断结果。 – 2015-07-28 14:36:52