方式一 时间戳
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 取两个时间段内天数
*/
public class test1 {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date star = dateFormat.parse("2020-02-03");//开始时间
Date endDay=dateFormat.parse("2025-03-02");//结束时间
Long starTime=star.getTime();
System.out.println("开始时间:"+starTime); // 时间戳:毫秒级,1s=1000ms
Long endTime=endDay.getTime();
System.out.println("结束时间:"+endTime);
Long num=endTime-starTime;//时间戳相差的毫秒数
System.out.println("相差天数为:"+num/24/60/60/1000);//除以一天的毫秒数
} catch (ParseException e) {
e.printStackTrace();
}
}
}
方式一方法抽取:
private int diffDays(String dateStart, String dateEnd) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date startDate = dateFormat.parse(dateStart.trim().substring(0, 8));
Date endDate = dateFormat.parse(dateEnd.trim().substring(0, 8));
return Math.abs((int) ((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000)));
}
方式二 util包的Calendar类
// 第二种:试用util包的Calendar类,每次增加一天,直到和结束时间相等的时候。
@Test
public void demo2() throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date star = dateFormat.parse("2020-02-03");
Date endDay = dateFormat.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);
}