需求:计算两个日期之间相差几个月份
说明:适用于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("------------------------------------------------");
}
}
}