2011-08-18 119 views

回答

114

好,開始時,你應該只交易與他們的字符串時,你必須。大多數情況下,您應該使用實際描述您正在使用的數據的數據類型與他們一起工作。

我會建議您使用Joda Time,這是一個比Date/Calendar更好的API。聽起來你應該在這種情況下使用LocalDate類型。然後,您可以使用:

int days = Days.daysBetween(date1, date2).getDays(); 
+0

好像這種方法獨佔不包括在內,因此可能希望將結果添加1(或將** 25 **(而不是24)小時添加到'date2')以使其變爲包含性。 –

+0

@AlaaM:好吧,*如果你想讓它變得包容。如果我被問到12月24日和12月25日之間的天數,我會說1,而不是2 ...(而且OP看起來似乎很開心。) –

+0

是的這就是爲什麼我說*可能需要*。在我的情況下,我需要顯示「剩餘天數到期」。所以在我看來,這種情況應該是包容性的 –

8

這裏是一個小程序,它可以幫助你:

import java.util.*; 

public class DateDifference { 
    public static void main(String args[]){ 
     DateDifference difference = new DateDifference(); 
    } 

    DateDifference() { 
     Calendar cal1 = new GregorianCalendar(); 
     Calendar cal2 = new GregorianCalendar(); 

     cal1.set(2010, 12, 1); 
     cal2.set(2011, 9, 31); 
     System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime())); 
    } 

    public int daysBetween(Date d1, Date d2) { 
     return (int)((d2.getTime() - d1.getTime())/(1000 * 60 * 60 * 24)); 
    } 
} 
+0

我會編輯的一件事是: ''' public long daysBetween(Date d1,Date d2){0122.JPG Time() - d1.getTime() )/(1000 * 60 * 60 * 24)); }''' – iamtodor

34

試試這個代碼

 Calendar cal1 = new GregorianCalendar(); 
    Calendar cal2 = new GregorianCalendar(); 

    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy"); 

    Date date = sdf.parse("your first date"); 
    cal1.setTime(date) 
    date = sdf.parse("your second date"); 
    cal2.setTime(date); 

    //cal1.set(2008, 8, 1); 
    //cal2.set(2008, 9, 31); 
    System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime())); 

此功能

 public int daysBetween(Date d1, Date d2){ 
      return (int)((d2.getTime() - d1.getTime())/(1000 * 60 * 60 * 24)); 
    } 
+0

這個方法將如何處理日光節約變化? – eldjon

+1

這個公式不錯,但它會少於1天。例如,d1 = 2016年1月2日和d2 = 2016年1月1日,它會給你1天而不是2天。 – stanicmail

+4

@stanicmail但2016年1月1日至1月2日期間只有一天!除非你在2015年12月31日喝得太多,當然。 ;-) – tomorrow

-5

如果」你可以選擇與java搞混了將它作爲查詢的一部分發送到db2:

select date1, date2, days(date1) - days(date2) from table 

將返回date1,date2和兩者之間的天數差。

7
// http://en.wikipedia.org/wiki/Julian_day 
public static int julianDay(int year, int month, int day) { 
    int a = (14 - month)/12; 
    int y = year + 4800 - a; 
    int m = month + 12 * a - 3; 
    int jdn = day + (153 * m + 2)/5 + 365*y + y/4 - y/100 + y/400 - 32045; 
    return jdn; 
} 

public static int diff(int y1, int m1, int d1, int y2, int m2, int d2) { 
    return julianDay(y1, m1, d1) - julianDay(y2, m2, d2); 
} 
-1

我的最佳解決方案(到目前爲止),用於計算天差數:

// This assumes that you already have two Date objects: startDate, endDate 
// Also, that you want to ignore any time portions 

Calendar startCale=new GregorianCalendar(); 
Calendar endCal=new GregorianCalendar(); 

startCal.setTime(startDate); 
endCal.setTime(endDate); 

endCal.add(Calendar.YEAR,-startCal.get(Calendar.YEAR)); 
endCal.add(Calendar.MONTH,-startCal.get(Calendar.Month)); 
endCal.add(Calendar.DATE,-startCal.get(Calendar.DATE)); 

int daysDifference=endCal.get(Calendar.DAY_OF_YEAR); 

但是請注意,這個假設不到一年的區別!

1

此功能是爲我好:

public static int getDaysCount(Date begin, Date end) { 
    Calendar start = org.apache.commons.lang.time.DateUtils.toCalendar(begin); 
    start.set(Calendar.MILLISECOND, 0); 
    start.set(Calendar.SECOND, 0); 
    start.set(Calendar.MINUTE, 0); 
    start.set(Calendar.HOUR_OF_DAY, 0); 

    Calendar finish = org.apache.commons.lang.time.DateUtils.toCalendar(end); 
    finish.set(Calendar.MILLISECOND, 999); 
    finish.set(Calendar.SECOND, 59); 
    finish.set(Calendar.MINUTE, 59); 
    finish.set(Calendar.HOUR_OF_DAY, 23); 

    long delta = finish.getTimeInMillis() - start.getTimeInMillis(); 
    return (int) Math.ceil(delta/(1000.0 * 60 * 60 * 24)); 
} 
27

在Java 8.您可以使用Enum ChronoUnit實例來計算的不同單位(日,月,秒)的時間量。

例如:

ChronoUnit.DAYS.between(startDate,endDate) 
19

我知道這個線程現在兩歲,我還沒有看到一個正確的答案在這裏。

除非你想使用喬達或具備Java 8,如果你需要subract由夏令影響日期。

所以我寫了我自己的解決方案。最重要的方面是,它只有在你真正關心的日期,因爲這是要丟棄的時間信息工作,所以如果你想要像25.06.2014 - 01.01.2010 = 1636,這應該不管DST的工作:

private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy"); 

public static long getDayCount(String start, String end) { 
    long diff = -1; 
    try { 
    Date dateStart = simpleDateFormat.parse(start); 
    Date dateEnd = simpleDateFormat.parse(end); 

    //time is always 00:00:00 so rounding should help to ignore the missing hour when going from winter to summer time as well as the extra hour in the other direction 
    diff = Math.round((dateEnd.getTime() - dateStart.getTime())/(double) 86400000); 
    } catch (Exception e) { 
    //handle the exception according to your own situation 
    } 
    return diff; 
} 

隨着時間的始終爲00:00:00,如果從冬季到夏季時間使用雙擊,然後Math.round()應該有助於忽略缺失的60000毫秒(1小時),以及從夏季到冬季需要額外的一小時。

這是我用一個小JUnit4測試來證明這一點:

@Test 
public void testGetDayCount() { 
    String startDateStr = "01.01.2010"; 
    GregorianCalendar gc = new GregorianCalendar(locale); 
    try { 
    gc.setTime(simpleDateFormat.parse(startDateStr)); 
    } catch (Exception e) { 
    } 

    for (long i = 0; i < 10000; i++) { 
    String dateStr = simpleDateFormat.format(gc.getTime()); 
    long dayCount = getDayCount(startDateStr, dateStr); 
    assertEquals("dayCount must be equal to the loop index i: ", i, dayCount); 
    gc.add(GregorianCalendar.DAY_OF_YEAR, 1); 
    } 
} 

...或者,如果你想看看它做什麼「生命」,只用更換斷言:

System.out.println("i: " + i + " | " + dayCount + " - getDayCount(" + startDateStr + ", " + dateStr + ")"); 

...這是輸出應該是什麼樣子:

i: 0 | 0 - getDayCount(01.01.2010, 01.01.2010) 
    i: 1 | 1 - getDayCount(01.01.2010, 02.01.2010) 
    i: 2 | 2 - getDayCount(01.01.2010, 03.01.2010) 
    i: 3 | 3 - getDayCount(01.01.2010, 04.01.2010) 
    ... 
    i: 1636 | 1636 - getDayCount(01.01.2010, 25.06.2014) 
    ... 
    i: 9997 | 9997 - getDayCount(01.01.2010, 16.05.2037) 
    i: 9998 | 9998 - getDayCount(01.01.2010, 17.05.2037) 
    i: 9999 | 9999 - getDayCount(01.01.2010, 18.05.2037) 
3

我真的真的真的在Java的新的,所以我敢肯定,有一個更好的方式來做我的建議。

我有這個相同的需求,我使用了兩個日期的DAYOFYEAR之間的差異。 似乎更簡單的方式來做到這一點...

我真的不能評估性能和穩定性方面這種解決方案,但我認爲這是確定。

這裏:

 
    public static void main(String[] args) throws ParseException { 



//Made this part of the code just to create the variables i'll use. 
//I'm in Brazil and the date format here is DD/MM/YYYY, but wont be an issue to you guys. 
//It will work anyway with your format. 

    String s1 = "18/09/2014"; 
    String s2 = "01/01/2014"; 
    DateFormat f = DateFormat.getDateInstance(); 
    Date date1 = f.parse(s1); 
    Date date2 = f.parse(s2); 




//Here's the part where we get the days between two dates. 

    Calendar day1 = Calendar.getInstance(); 
    Calendar day2 = Calendar.getInstance(); 
    day1.setTime(date1); 
    day2.setTime(date2); 

    int daysBetween = day1.get(Calendar.DAY_OF_YEAR) - day2.get(Calendar.DAY_OF_YEAR);  




//Some code just to show the result... 
    f = DateFormat.getDateInstance(DateFormat.MEDIUM); 
    System.out.println("There's " + daysBetween + " days between " + f.format(day1.getTime()) + " and " + f.format(day2.getTime()) + "."); 



    } 

在這種情況下,輸出將是(記住,我使用的日期格式DD/MM/YYYY):

 
There's 260 days between 18/09/2014 and 01/01/2014. 
+0

這不起作用,因爲它只會告訴你一年中的日子與總的日子之間的差異。 – Stosh15