兩個日期之間相差的月數
阿新 • • 發佈:2018-11-25
在網上看了一下別人的解決方法,直接粗暴的獲取日期的月份,相減就給出答案,這不是我想要的,因為這個完全沒意義:
兩個日期跨年了怎麼辦,如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 }