需求:获取两个Date时间间隔的天数,并依次输出每一天.
示例:
两个时间: [2018-10-01,2018-10-05) 时间间隔: 4 输出时间: Mon Oct 01 00:00:00 CST 2018 Tue Oct 02 00:00:00 CST 2018 Wed Oct 03 00:00:00 CST 2018 Thu Oct 04 00:00:00 CST 2018
代码实现具体如下:
package hrt.executor.test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateBetweenTest { public static void main(String[] args) throws ParseException { Calendar compareDay = new GregorianCalendar(); //Calendar compareDay = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String startStr = "2018-10-01"; String endStr = "2018-10-05"; Date startDate = sdf.parse(startStr); Date endDate = sdf.parse(endStr); int differentDays = differentDays(startDate, endDate); System.out.println(startStr + " ~ " + endStr + " ,间隔天数为" + differentDays); for (int i = 0; i < differentDays; i++) { compareDay.setTime(startDate); compareDay.add(compareDay.DATE, i); System.out.println(compareDay.getTime()); } } /** * date2比date1多的天数:比较是基于年月日做的比较,不计算时分秒 * * @param date1 * @param date2 * @return */ public static int differentDays(Date date1, Date date2) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); int day1 = cal1.get(Calendar.DAY_OF_YEAR); int day2 = cal2.get(Calendar.DAY_OF_YEAR); int year1 = cal1.get(Calendar.YEAR); int year2 = cal2.get(Calendar.YEAR); if (year1 != year2) // 不同年 { int timeDistance = 0; for (int i = year1; i < year2; i++) { if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) // 闰年 { timeDistance += 366; } else // 不是闰年 { timeDistance += 365; } } return timeDistance + (day2 - day1); } else // 同一年 { // System.out.println("判断day2 - day1 : " + (day2-day1)); return day2 - day1; } } }
执行结果如下:
网络异常,图片无法展示
|
代码运行结果截图