两个日期之间相差的月数

在网上看了一下别人的解决方法,直接粗暴的获取日期的月份,相减就给出答案,这不是我想要的,因为这个完全没意义:

两个日期跨年了怎么办,如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
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值