版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20417499/article/details/82500406
在网上看了一下别人的解决方法,直接粗暴的获取日期的月份,相减就给出答案,这不是我想要的,因为这个完全没意义:
两个日期跨年了怎么办,如2017-01-02 到2018-12-13相差几个月? 拿 1减去12吗。。
后面自己实现了一下:
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Calendar;
@RestController
public class Test {
@RequestMapping(value = "/", method = RequestMethod.GET)
public void test() {
DateTime startTime = new DateTime("2017-12-1");
DateTime endTime = new DateTime("2018-7-29");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(startTime.toDate());
c2.setTime(endTime.toDate());
int between = 0;
while ((c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) || (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) ) {
startTime = startTime.plusMonths(1);
c1.setTime(startTime.toDate());
between = between + 1;
System.out.println("startTime" + startTime);
System.out.println("endTime" + endTime);
System.out.println(c1.get(Calendar.YEAR) );
System.out.println(c2.get(Calendar.YEAR));
System.out.println(c1.get(Calendar.MONTH) );
System.out.println(c2.get(Calendar.MONTH));
}
System.out.println(between); //7
}