2012-03-17 80 views

回答

3

這應該工作 其Java代碼。 只是修改了Android

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(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

我認爲這段代碼在很多時候寫在stackoverflow中 – 2012-03-17 11:28:14

+0

我剛剛做了一個快速的谷歌搜索 – mpeerman 2012-03-17 11:30:16

+0

我也做過,但這段代碼已經完成了很多次,並且在stackoverflow中寫了很多次,所以刪除它 – 2012-03-17 11:31:29

1

的的compareTo()方法的工作(如果你使用數據/日期()爲例),只會給你的是:

返回一個整數,指示是否此實例早於, 相同或晚於指定的Date/DateTime值。 (MSDN)

這就是爲什麼你只得到-1和1天的不是數字之間的數字(你可以在MSDN檢查befor

爲了做到你想要什麼,看看這個帖子:Number of days between 2 dates

1

我希望這將有助於你

import java.util.*; import java.util.Calendar; 

public class DeltaDays { public static void main(String[] args) { 
// Creates two calendars instances 

Calendar calendar1 = Calendar.getInstance(); Calendar calendar2 = Calendar.getInstance(); 

// Set the date for both of the calendar instance 
calendar1.set(2007, 12, 30); calendar2.set(2008, 05, 03); 

// Get the represented date in milliseconds 
long milis1 = calendar1.getTimeInMillis(); long milis2 = calendar2.getTimeInMillis(); 

// Calculate difference in milliseconds 
long day = milis2 - milis1; 

// Calculate difference in seconds 
long diffSeconds = day/1000; 

// Calculate difference in minutes 
long diffMinutes = day/(60 * 1000); 

// Calculate difference in hours 
long diffHours = day/(60 * 60 * 1000); 

// Calculate difference in days 
long diffDays = day/(24 * 60 * 60 * 1000); 

System.out.println("In milliseconds: " + day + " milliseconds."); 
System.out.println("In seconds: " + diffSeconds + " seconds."); 
System.out.println("In minutes: " + diffMinutes + " minutes."); 
System.out.println("In hours: " + diffHours + " hours."); 
System.out.println("In days: " + diffDays + " days."); } } 
0

試試這個,使用dateDifference()在你的Android項目的方法:

import java.util.Calendar; 
import java.util.Date; 

public class Sample { 

public static void main(String arg[]) 
{ 

dateDifference(); 

} 

public static void dateDifference() 
{ 
Date currentdate = new Date(); 
Calendar calUpdated = Calendar.getInstance(); 
calUpdated.set(2012, 01, 01); 
long currentDateMilliSec = currentdate.getTime(); 
long updateDateMilliSec = calUpdated.getTimeInMillis(); 
long diffDays = (currentDateMilliSec - updateDateMilliSec)/(24 * 60 * 60 * 1000); 
System.out.println("Time in days: " + diffDays + " days."); 
} 
}