我正面临着如何通过比较2个日期来获得已经过去的天数的问题。目前我尝试使用compareTo()但它只返回1或-1,我想获得已经过去的天数。 Thannks
答案 0 :(得分: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));
}
}
答案 1 :(得分:1)
compareTo()方法(如果使用Data / DateTime()作为示例)只会给你:
返回一个整数,指示此实例是否早于 与指定的Date / DateTime值相同或晚于指定的Date / DateTime值。 (MSDN)
这就是为什么你只得到介于-1和1之间的数字而不是天数(你可以在MSDN上检查
为了做你想做的事,请查看这篇文章:Number of days between 2 dates
答案 2 :(得分: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."); } }
答案 3 :(得分:0)
试试这个,在你的android项目中使用dateDifference()方法:
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.");
}
}