2010-08-17 56 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