抱歉,我试过参考Similar Method中的方法。但我仍然无法得到解决方案。如何获得两个不同日期之间的输出月份和天数?任何帮助将不胜感激。谢谢。
P / s:JodaTime不适用。
到目前为止我尝试了什么。
SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-yyyy");
String start = "03-01-2015";
String end = "01-11-2014";
Date startdate = formatter.parse(start);
Date enddate = formatter.parse(end);
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startdate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(enddate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) -startCalendar.get(Calendar.MONTH);
答案 0 :(得分:1)
希望这就是你想要的。
int diffDay= endCalendar.get(Calendar.DAY_OF_MONTH) -startCalendar.get(Calendar.DAY_OF_MONTH);
System.err.println("diffMonth==="+diffMonth +" Month(s) and " + diffDay + " Day(s)");
答案 1 :(得分:0)
在java8中你可以这样做:
LocalDate startDate = LocalDate.of(2004, Month.JANUARY, 1);
LocalDate endDate = LocalDate.of(2005, Month.JANUARY, 1);
long monthsInYear2 = ChronoUnit.MONTHS.between(startDate, endDate);
(来源:http://www.leveluplunch.com/java/examples/number-of-months-between-two-dates/)