我有两个约会(01/01/2012,2014年7月31日)。
请你帮我计算这两个日期之间的月差。 如果差异是8个月1天我需要结果9个月。
答案 0 :(得分:8)
Working Code:
public int monthsBetweenDates(Date startDate, Date endDate){
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
int monthsBetween = 0;
int dateDiff = end.get(Calendar.DAY_OF_MONTH)-start.get(Calendar.DAY_OF_MONTH);
if(dateDiff<0) {
int borrrow = end.getActualMaximum(Calendar.DAY_OF_MONTH);
dateDiff = (end.get(Calendar.DAY_OF_MONTH)+borrrow)-start.get(Calendar.DAY_OF_MONTH);
monthsBetween--;
if(dateDiff>0) {
monthsBetween++;
}
}
else {
monthsBetween++;
}
monthsBetween += end.get(Calendar.MONTH)-start.get(Calendar.MONTH);
monthsBetween += (end.get(Calendar.YEAR)-start.get(Calendar.YEAR))*12;
return monthsBetween;
}
答案 1 :(得分:5)
您可以使用Calendar
之类的
static int monthsBetween(Date a, Date b) {
Calendar cal = Calendar.getInstance();
if (a.before(b)) {
cal.setTime(a);
} else {
cal.setTime(b);
b = a;
}
int c = 0;
while (cal.getTime().before(b)) {
cal.add(Calendar.MONTH, 1);
c++;
}
return c - 1;
}
然后你可以称之为
public static void main(String[] args) {
String start = "01/01/2012";
String end = "31/07/2014";
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
System.out.println(monthsBetween(sdf.parse(start), sdf.parse(end)));
} catch (ParseException e) {
e.printStackTrace();
}
}
输出
30
或者,使用Joda-Time
String start = "01/01/2012";
String end = "31/07/2014";
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
LocalDate a = LocalDate.fromDateFields(sdf.parse(start));
LocalDate b = LocalDate.fromDateFields(sdf.parse(end));
Period p = new Period(a, b);
System.out.println((p.getYears() * 12) + p.getMonths());
} catch (ParseException e) {
e.printStackTrace();
}
输出也是
30
修改强>
最后(如评论中所述),如果您使用的是Java 8,则可以使用新的java.time
类,如
String start = "01/01/2012";
String end = "31/07/2014";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate from = LocalDate.parse(start, formatter);
LocalDate to = LocalDate.parse(end, formatter);
System.out.println(from.until(to, ChronoUnit.MONTHS));
输出是(仍然)
30
答案 2 :(得分:0)
我的代码:
int getMonthCountBetween(Calendar cal1, Calendar cal2) {
if(cal1.compareTo(cal2)>0) {
Calendar cal=cal1;
cal1=cal2;
cal2=cal;
}
int months=0;
int y1 = cal1.get(Calendar.YEAR);
int y2 = cal2.get(Calendar.YEAR);
int m1 = cal1.get(Calendar.MONTH);
int m2 = cal2.get(Calendar.MONTH);
if (y2 - y1 >= 0) {
months = m2 - m1 + 1;
}
if (y2 - y1 >= 1) {
months += 12;
}
if (y2 - y1 >= 2) {
months += 12 * (y2 - y1 - 1);
}
return months;
}
答案 3 :(得分:0)
int months = 12*(toYear-fromYear)+(toMonth-fromMonth)+(toDay>=fromDay?1:0)
哪里是以后的日期,从哪里是以前的日期