java计算日期相差天数的4种方法

时间:2025-02-10 07:50:03

方法1:long值相减(推荐)

public static void main(String[] args) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 try {
		        Date startDate = ("2024-03-01 10:00:00");//开始时间
		        Date endDate = ("2024-03-02 14:00:00");//结束时间
		        long msNum = ()-();//时间戳相差的毫秒数
                long dayNum = msNum/(24*60*60*1000)//除以一天的毫秒数,得到相差天数
		        ("相差天数为:"+ dayNum);
		 } catch (ParseException e) {
		        ();
		 }
}

方法2:

public static void main(String[] args) {
		DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
	    try {
	        Date star = ("2020-02-03");//开始时间
	        Date endDay=("2025-03-02");//结束时间
	        Date nextDay=star;
	        int i=0;
	        while((endDay)){//当明天不在结束时间之前是终止循环
	        	Calendar cld = ();
	 	        (star);
	 	        (, 1);
	 	        star = ();
	 	        //获得下一天日期字符串
	 	        nextDay = star; 
	 	        i++;
	        }
	       ("相差天数为:"+i);
	    } catch (ParseException e) {
	        ();
	    }
	}

方法3:

public static void main(String[] args) {
		String star="2020-02-03";
		String end="2025-03-02";
		String[] star1=("-");
		String[] end1=("-");
		int days=0;
		if((star1[0])<(end1[0])){
			for(int i=(star1[0]);i<(end1[0]);i++){
				//计算是否是瑞年
				if(i%4==0&&i%100!=0||i%400==0){
					days+=366;
				}else{
					days+=365;
				}
			}
		}
		//得到开始那一年已过去的日期
		int starday=days(star1[0],star1[1],star1[2]);
		//得到结束那一年已过去的日期
		int endday=days(end1[0],end1[1],end1[2]);
		//减去开始那一年已过去的日期,加上结束那一年已过去的日期
		days=days-starday+endday;
		("相差的天数:"+days);
	}
	public static int days(String year,String month,String day){
		int days=0;
		int nowyear=(year);
		int[] monthday={0,31,28,31,30,31,30,31,31,30,31,30,31};
		int[] monthday1={0,31,29,31,30,31,30,31,31,30,31,30,31};
		boolean flag=true;
		if(nowyear%4==0&&nowyear%100!=0||nowyear%400==0){
		}else{
			flag=false;
		}
		for(int i=0;i<(month);i++){
			if(flag){
				days+=monthday1[i];
			}else{
				days+=monthday[i];
			}
		}
		days+=(day);
		return days;
	}

方法4:

int y;
	int m;
	int d;

	public test2(int y,int m,int d ){
		=y;
		=m;
		=d;
	}
	public int sum(test2 d){
		int day=0;
		int[] x={0,31,28,31,30,31,30,31,31,30,31,30,31};
		for(int i=1;i<;i++){
			if(i%4==0&& i%100!=0 || i%400==0){
				day+=366;
			}else{
				day+=365;
			}
		}
		if(%4==0&& %100!=0 || %400==0){
			x[2]=29;
		}
		for(int i=1;i<;i++){

			day+=x[i];	
		}
		day+=;
		(day);
		return day;

	}
	public int DiffDays(test2 d){//计算两个日期之间的相距天数的成员方法 
		int s1=sum(this);
		int s2=sum(d);
		if(s1>s2){
			return s1-s2;
		}else{
			return s2-s1;
		}
	}
	public static void main(String args[]){ 
		int a,b,c; 
		test2 d1,d2; 
		try{ 
			d1=new test2(2020,02,03); 
			d2=new test2(2025,03,02); 
			("相差的天数:"+(d2)); 
		}catch(Exception e){ 
			("error"); 
		} 
	}