java计算日期相差天数的4种简单方法举例

来自:网络
时间:2024-09-10
阅读:

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

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

方法2:

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

方法3:

public static void main(String[] args) {
		String star="2020-02-03";
		String end="2025-03-02";
		String[] star1=star.split("-");
		String[] end1=end.split("-");
		int days=0;
		if(Integer.parseInt(star1[0])<Integer.parseInt(end1[0])){
			for(int i=Integer.parseInt(star1[0]);i<Integer.parseInt(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;
		System.out.println("相差的天数:"+days);
	}
	public static int days(String year,String month,String day){
		int days=0;
		int nowyear=Integer.parseInt(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<Integer.parseInt(month);i++){
			if(flag){
				days+=monthday1[i];
			}else{
				days+=monthday[i];
			}
		}
		days+=Integer.parseInt(day);
		return days;
	}

方法4:

int y;
	int m;
	int d;

	public test2(int y,int m,int d ){
		this.y=y;
		this.m=m;
		this.d=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<d.y;i++){
			if(i%4==0&& i%100!=0 || i%400==0){
				day+=366;
			}else{
				day+=365;
			}
		}
		if(d.y%4==0&& d.y%100!=0 || d.y%400==0){
			x[2]=29;
		}
		for(int i=1;i<d.m;i++){

			day+=x[i];	
		}
		day+=d.d;
		System.out.println(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); 
			System.out.println("相差的天数:"+d1.DiffDays(d2)); 
		}catch(Exception e){ 
			System.out.println("error"); 
		} 
	}

附:计算两个日期相差天数(除去双休日)

首先可以将问题简化一下,可以知道,不论开始、结束日期,只要经过7天,必定就有两天是周末。因此问题可以简化为,一周内的双休日天数+周数*2.

public int checkWeekendDay(int startDate, int endDate, int days){
        int weekEndCount = 0;
        if (days<1){
            if (startDate==6 || startDate==0){
                weekEndCount+=1;
            }
        } else {
            weekEndCount+=(days/7)*2;
            weekEndCount+=calculateWeekendDays(startDate,endDate);
        }

        return weekEndCount;
    }

public int calculateWeekendDays(int startDate, int endDate){
        int weekendCount=0;
        if (startDate==0&&endDate==6) {
            weekendCount += 2;
        }else if (startDate<endDate&&endDate==6){
            weekendCount+=1;
        }else if (startDate<endDate&&startDate==0){
            weekendCount+=1;
        }else if (startDate>endDate){
            weekendCount+=2;
        }
        if (startDate==endDate){
            if (startDate==6||endDate==0){
                weekendCount+=1;
            }
        }

        return weekendCount;
    }

总结 

返回顶部
顶部