2017-01-13 45 views
0

我試圖在兩個日期之間的天數中找出差異。 我使用這種方法兩天之間的日期差異不能給出正確的結果

Calendar currentTimeCalendar = Calendar.getInstance(); 
    Calendar postModificationTimeCalendar = Calendar.getInstance(); 
    postModificationTimeCalendar.setTime(dateeventoccured); //dateeventoccured is in format = Tue Jan 03 00:44:46 EST 2017 

    long diffInMillis = currentTimeCalendar.getTimeInMillis() - postModificationTimeCalendar.getTimeInMillis(); 
    long days = diffInMillis/ (24*60*60*1000); 

現在的問題是假設,昨天我的東西下午5時許,當它在午夜12今天的區別應該是1和日期應該是如昨。

但是天仍然是0,直到第二天達到5。如何實現這一點。 我想將日期顯示爲今天,昨天和以前的日期。

+0

唔,我會建議你使用LocalDateTime API或者如果你是在舊的Java版本,約達時間 – Dexter

+0

你有沒有考慮使用['Java.time.LocalDate'(https://docs.oracle。 com/javase/8/docs/api/java/time/LocalDate.html)或['org.joda.time.LocalDate'](http://www.joda.org/joda-time/apidocs/org/joda /time/LocalDate.html)? –

+0

[獲取自Java中的Epoch以來的天數,週數和月數]的可能重複(http://stackoverflow.com/questions/6158053/get-the-number-of-days-weeks-and-months-因爲-劃時代在-java的) – AxelH

回答

0

試試這個(通過2個日期在這個函數對象,你會得到確切的DIFF在天2日期間):

public long getDays(Date d1, Date d2) { 
     if (d1 != null && d2 != null) { 
      long diff = getStartDate(d1).getTimeInMillis() - getStartDate(d2).getTimeInMillis(); 
      return TimeUnit.MILLISECONDS.toDays(diff); 
     } else { 
      return -1; 
     } 
    } 

    public Calendar getStartDate(Date date){ 
     Calendar cal = Calendar.getInstance(); 
     cal.setTime(date); 
     cal.set(Calendar.HOUR_OF_DAY, 0); 
     cal.set(Calendar.MINUTE, 0); 
     cal.set(Calendar.SECOND, 0); 
     cal.set(Calendar.MILLISECOND, 0); 
     return cal; 
    } 
0
private int getDifferenceDay(Date DateStart, Date DateEnd) { 
    long diff = DateEnd.getTime() - DateStart.getTime(); 
    long seconds = diff/1000; 
    int minutes = (int) seconds/60; 
    int hour = minutes/60; 
    int day = hour/24; 
    return day; 
} 
0

嘗試使用comareTo方法,將返回的時間差作爲整數值。 private void getDate()throws ParseException SimpleDateFormat sdf = new SimpleDateFormat(「yyyy-dd-mm」); String date1 =「2017-13-01」; String date2 =「2017-14-01」;

Date d1=sdf.parse(date1); 
Date d2=sdf.parse(date2); 

int compare = d2.compareTo(d1); 
Log.e("differece",""+compare); 
}