两个日期之间的那点事

准备工作

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String start = "2020-12-15";
String end = "2021-6-7";
Date start1 = sdf.parse(start);
Date end1 = sdf.parse(end);

获取两个日期之间的天数

long days = (end1.getTime() - start1.getTime()) / (24*3600*1000);
System.out.println(days+"天");//174天

番外:

//当其中一个日期为 new Date()实时获取时,需要对获取的时间的时分秒进行处理,否则容易存在误差
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String end = "2020-12-18";
Date end1 = sdf.parse(end);

Date start1 = new Date();//2020-12-15
start1.setHours(0);
start1.setMinutes(0);
start1.setSeconds(0);
long days = (end1.getTime() - start1.getTime()) / (24*3600*1000);
System.out.println(days);//2