方法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])方法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;is2){ 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 (startdateenddate){ weekendcount =2; } if (startdate==enddate){ if (startdate==6||enddate==0){ weekendcount =1; } } return weekendcount; } 总结