问题:
怎样通过日期类确定两个日期相隔几天?
语言:java, IDE:idea, 框架:springMVC。
代码:
主函数:
public static void main(String[] args) throws ParseException{
String nowDay = "2018-02-28";
String lastDay = "2018-03-01";
int x = subDay(lastDay, nowDay);
System.out.println(x);
}
public static int subDay(String lastTime, String nowTime) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date nowDate = sdf.parse(nowTime);
Date lastDate = sdf.parse(lastTime);
return subtract(nowDate, lastDate);
}
public static int subtract(Date date1, Date date2) {
return (Math.abs((int) date1.getTime() - (int) date2.getTime()) / 3600000) / 24;
}
结果会输出1.