我有两个日期的月,日和年的整数。如何计算它们之间的差异是否大于20年?我在注册新用户时使用了这个。
答案 0 :(得分:5)
使用Joda-Time,期间! :)
虽然“超过20年”可能在某种程度上取决于您正在谈论的日历类型,当您开始计算,闰年或夏令时时,Joda-Time将为您提供util.Calendar的更多灵活性类。不建议使用util.Date,计算毫秒(或其他类似的东西)可能会导致错误的代码。
JODA-TIME代码示例:
假设:
int year1 = 2012, month1 = 2, day1 = 7;
int year2 = 1987, month2 = 7, day2 = 23;
//You can include a TimeZone if needed in the constructors below
DateTime dateTime1 = new DateTime(year1, month1, day1, 0, 0); //2012-02-07T00:00:00.000-05:00
DateTime dateTime2 = new DateTime(year2, month2, day2, 0, 0); //1987-07-23T00:00:00.000-04:00
选项1,无聊......
DateTime twentyYearsBefore = dateTime1.minusYears(20); //1992-02-07T00:00:00.000-05:00
if(dateTime2.compareTo(twentyYearsBefore) == -1)
System.out.println("The difference between the dates is greater than 20 years");
选项2,好东西!
Days d = Days.daysBetween(dateTime1, dateTime2);
int days = d.getDays(); //-8965 days
System.out.println("There are " + days + " days between the two dates");
选项3,火箭科学! ;)
Period periodDifference = new Period(dateTime1, dateTime2);
System.out.println(periodDifference); //prints: P-24Y-6M-2W-1D
的API
答案 1 :(得分:2)
Calendar Day1 = Calendar.getInstance();
Day1.set(Calendar.DAY_OF_MONTH, day1 - 1);
Day1.set(Calendar.MONTH, month1 - 1); // 0-11 so 1 less
Day1.set(Calendar.YEAR, year1);
Calendar Day2 = Calendar.getInstance();
Day2.set(Calendar.DAY_OF_MONTH, day2 - 1);
Day2.set(Calendar.MONTH, month2 - 1); // 0-11 so 1 less
Day2.set(Calendar.YEAR, year2);
long twenty_years = 31536000000 * 20;
long diff;
if(Day1.compareTo(Day2) == 1)
long diff = Day1.getTimeInMillis() - Day2.getTimeInMillis();
else
long diff = Day2.getTimeInMillis() - Day1.getTimeInMillis();
if(diff > twenty_years){
// do something
}
答案 2 :(得分:2)
我觉得应该做的很简单。
double date1 = year + (month / 12.0) + (day / 365.0);
double date2 = year2 + (month2 / 12.0) + (day2 / 365.0);
if(Math.abs(date1 - date2) >= 20.0)
//bigger
答案 3 :(得分:1)
这是一种非常简单的方法;
int date1 = year1 * 10000 + month1 * 100 + day1;
int date2 = year2 * 10000 + month2 * 100 + day2;
boolean greaterThan20 = (date2 - date1) >= 200000;
答案 4 :(得分:1)
答案 5 :(得分:1)
您可以使用
Date(int year, int month, int date)
将您的值转换为日期格式。
然后你可以从另一个中减去一个并将值转换成几年。
java.util.Date lateDate, earlyDate;
lateDate = Date(year1,month1,day1);
earlyDate = Date(year2,month2,day2);
deltaDays = ( lastDate.getTime() - earlyDate.getTime() )/ MILLSECS_PER_DAY;
deltaDays = deltaDays / DAYS_IN_A_YEAR;