java计算两个日期间的天数
精确到年月日
public static int daysBetween(Date start, Date end) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { start = sdf.parse(sdf.format(start)); end = sdf.parse(sdf.format(end)); } catch (ParseException e) { e.printStackTrace(); } long startTime = start.getTime(); long endTime = end.getTime(); long betweenDays = (endTime - startTime) / (1000 * 3600 * 24); return Integer.parseInt(String.valueOf(betweenDays)); }
精确到秒,向下取值
public static int daysBetween(Date start, Date end) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { start = sdf.parse(sdf.format(start)); end = sdf.parse(sdf.format(end)); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(start); long startTime = cal.getTimeInMillis(); cal.setTime(end); long endTime = cal.getTimeInMillis(); long betweenDays = (endTime - startTime) / (1000 * 3600 * 24); return Integer.parseInt(String.valueOf(betweenDays)); }
如有问题,欢迎指正~ 如能帮到您,欢迎点赞收藏~
来源地址:https://blog.csdn.net/qq_40240091/article/details/129055104