用户输入了:1949-11-1 程序输出:31
/*startYear~endYear,年度之间的天数 *计算Month月day天是year年的第几天 *确定year年是平年还是闰年 *闰年的标准为,能被4整除,不能被100整除,或者是能被400整除 */ import java.util.Scanner; public class Main{ //新建两个数组,保存每年的天数和每月的天数 public static int[] dayOfYear={365,366}; public static int[][] dayOfMonth={ {0,31,28,31,30,31,30,31,31,30,31,30,31}, {0,31,29,31,30,31,30,31,31,30,31,30,31} }; //判断是平年还是闰年,平年返回0,闰年返回1 public static int getYear(int year){ if((year%4==0&&year%100!=0)||year%400==0){ return 1; } return 0; } //判断startYear到endYear之间的天数 public static int getDayOfYear(int startYear,int endYear){ int days=0; for(int i=startYear;i<endYear;i++){ days+=dayOfYear[getYear(i)]; } return days; } //判断month月day天是year年的第几天 public static int getDayOfMonth(int year,int month,int day){ int days=0; for(int i=1;i<month;i++){ days+=dayOfMonth[getYear(year)][i]; } days+=day; return days; } //根据输入的时间计算相隔天数 public static int getDepart(String startDate,String endDate){ //分离出两个时间的年、月、日 String s1[]=startDate.split("-"); String s2[]=endDate.split("-"); //起始年 int startYear=Integer.parseInt(s1[0]); int endYear=Integer.parseInt(s2[0]); //起始月 int startMonth=Integer.parseInt(s1[1]); int endMonth=Integer.parseInt(s2[1]); //起始日 int startDay=Integer.parseInt(s1[2]); int endDay=Integer.parseInt(s2[2]); int days=0; //计算年与年之间的时间间隔 days+=getDayOfYear(startYear,endYear); days-=getDayOfMonth(startYear,startMonth,startDay); days+=getDayOfMonth(endYear,endMonth,endDay); return days; } public static void main(String[] args){ Scanner s=new Scanner(System.in); String endDate=s.nextLine(); String startDate="1949-10-1"; System.out.println(getDepart(startDate,endDate)); } }