java中两个日期之间的天数
比如:2020-05-06 到 2020-05-07
返回两天 代码如下
1 public class test { 2 public static int b; 3 public static void main(String[] args) {13 14 String s1="2020-05-06"; 15 String s2="2020-05-07"; 16 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); 17 try { 18 Date date = simpleDateFormat.parse(s1); 19 Date date1 = simpleDateFormat.parse(s2); 20 int i = differentDays(date,date1); 21 System.out.println(i+1); 22 } catch (ParseException e) { 23 e.printStackTrace(); 24 } 25 26 } 27 28 /** 29 * date2比date1多的天数 30 * @param date1 31 * @param date2 32 * @return 33 */ 34 public static int differentDays(Date date1, Date date2) 35 { 36 Calendar cal1 = Calendar.getInstance(); 37 cal1.setTime(date1); 38 39 Calendar cal2 = Calendar.getInstance(); 40 cal2.setTime(date2); 41 int day1= cal1.get(Calendar.DAY_OF_YEAR); 42 int day2 = cal2.get(Calendar.DAY_OF_YEAR); 43 44 int year1 = cal1.get(Calendar.YEAR); 45 int year2 = cal2.get(Calendar.YEAR); 46 if(year1 != year2) //同一年 47 { 48 int timeDistance = 0 ; 49 for(int i = year1 ; i < year2 ; i ++) 50 { 51 if(i%4==0 && i%100!=0 || i%400==0) //闰年 52 { 53 timeDistance += 366; 54 } 55 else //不是闰年 56 { 57 timeDistance += 365; 58 } 59 } 60 61 return timeDistance + (day2-day1) ; 62 } 63 else //不同年 64 { 65 return day2-day1; 66 } 67 } 68 }