java计算两个日期之间的月份差

需求:计算两个日期之间相差几个月份

说明:适用于yyyyMMdd、yyyy-MM-dd、yyyy/MM/dd、yyyyMM、yyyy-MM、yyyy/MM格式的日期   


package demo;

import java.util.Scanner;


public class TestMonths {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		for(;;) {
			System.out.println("请输入第一个日期:");
			String time1 = sc.nextLine();
			System.out.println("请输入第二个日期:");
			String time2 = sc.nextLine();
			
			if((time1.length() <= 0 || time1 == null) || (time2.length() <= 0 || time2 == null)) {
				System.out.println("日期输入有误,请重新输入!");
				System.out.println("------------------------------------------------");
				continue;
			}
			
			Integer year1 = Integer.valueOf(time1.substring(0, 4));
			Integer year2 = Integer.valueOf(time2.substring(0, 4));
			Integer month1;
			Integer month2;
			
			if((time1.contains("-") || time1.contains("/")) || (time2.contains("-") || time2.contains("/"))) {
				month1 = Integer.valueOf(time1.substring(5, 7));
				month2 = Integer.valueOf(time2.substring(5, 7));
			}else {
				month1 = Integer.valueOf(time1.substring(4, 6));
				month2 = Integer.valueOf(time2.substring(4, 6));
			}
			
			if(month1 > 12 || month2 > 12) {
				System.out.println("月份输入有误,请重新输入!");
				System.out.println("------------------------------------------------");
				continue;				
			}

			Integer months1 = Math.abs((year1 - year2) * 12);
			Integer months2 = Math.abs(month1 - month2);		
			System.out.println(time1 + "与" + time2 + "相差"  + (months1 + months2) + "个月" );
			System.out.println("------------------------------------------------");
		}
	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.Righter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值