2014-10-27 59 views
-1

我正在使用Java獲取兩個日期之間的天數。當我將應用程序日期設置爲27時,顯示爲0,當我給出26時,它甚至顯示爲0.我的代碼中是否有任何錯誤?任何想法將不勝感激。使用Java在兩天之間無法獲得確切的天數差異

這裏是我的代碼

public static void main (String[] args) throws java.lang.Exception {    
     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     Date currentDate = new Date(); 
     System.out.println("Current date:"+dateFormat.format(currentDate)); 
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     String strAppDate = "2014-10-28 15:11:30.0"; 
     Date appDate = formatter.parse(strAppDate); 
     System.out.println("Application date :"+formatter.format(appDate)); 
     long diff = appDate.getTime() - currentDate.getTime(); 
     long diffDays = diff/(24 * 60 * 60 * 1000); 
     System.out.println("Diff days :"+diffDays); 
    } 
+0

適合我。看看這裏:http://ideone.com/I6RDS3 – 2014-10-27 12:24:56

+1

似乎沒問題。它只會給全天的人數。在我的時區,2014年10月26日15:11:30.0和現在還沒有完整的一天。 – Henry 2014-10-27 12:26:37

回答

1

您可以用這種方式嘗試。使用TimeUnit.MILLISECONDS.toDays()

long duration = appDate.getTime() - currentDate.getTime(); 
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration); 
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration); 
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration); 
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration); // number of days 
0

如果是小於差一天,除法運算的結果將是零,因爲這是如何的整數(長整型)部門工作。您可以嘗試除以double的值:

double diffDays = diff/(24 * 60 * 60 * 1000.0); 
1

您需要確定業務規則。如果不到一天的差異,例如23小時,您是否想將其計爲0或四捨五入爲1?

strAppDate"2014-10-28 15:11:30.0",並depnding你的時區,currentDate是27個,所以appDate.getTime()currentDate.getTime()之間的差小於24小時,long diffDays = diff/(24 * 60 * 60 * 1000);將爲零。

您可以使用雙打併始終四捨五入,或者您可以有一些規則根據小時差異確定天數差異。這真的取決於你需要多少精度。

相關問題