public class CalculateIntervalBetween2Dates { private static final long DAY=24*60*60*1000; private static final long HOUR=60*60*1000; private static final long MINUTES=60*1000; private static final long SECONDS=1000; private static final long MILLIONSECONDS=1;
/** * List dates between start date and end date, including the start date and end date. * @param startDateStr * @param endDateStr */ public static void listNumberOfDates(String startDateStr,String endDateStr){ SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); Date startDate = null; Date endDate = null; try { startDate = sf.parse(startDateStr); endDate = sf.parse(endDateStr); } catch (ParseException e) { e.printStackTrace(); } Calendar c1 = Calendar.getInstance(); List<Date> cancelDates = new ArrayList<Date>(); if (startDate != null && endDate != null && startDate.before(endDate)) { Date tempDate = startDate; do { cancelDates.add(tempDate); c1.setTime(tempDate); c1.add(Calendar.DAY_OF_MONTH, 1); tempDate = c1.getTime(); } while (tempDate.before(endDate)); cancelDates.add(endDate); }
System.out.println("There are " + cancelDates.size() + " days between " + sf.format(startDate) + " and " + sf.format(endDate) + ", inclusive."); System.out.println("See the following list:"); for (Date date : cancelDates) { System.out.println(sf.format(date)); } System.out.println(); }
/** * Calculate how many days/hours/minutes/seconds/million seconds between start date and end date, including the start date and end date. * @param startDateStr * @param endDateStr * @param interval */ public static void calculateInterval(String startDateStr,String endDateStr,long interval){ SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); Date startDate = null; Date endDate = null; try { startDate = sf.parse(startDateStr); endDate = sf.parse(endDateStr); } catch (ParseException e) { e.printStackTrace(); } Calendar c1 = Calendar.getInstance(); c1.setTime(startDate); long startInMillis=c1.getTimeInMillis(); c1.setTime(endDate); //inclusive,2009/10/24-2009/10/23=1,but actually 2 days c1.add(Calendar.DAY_OF_MONTH, 1);
long endInMillis=c1.getTimeInMillis(); long between=endInMillis-startInMillis; System.out.println("There are " + (between/interval) +" "+getIntervalLabel(interval) + " between " + sf.format(startDate) + " and " + sf.format(endDate) + ", inclusive"); }