获取两个时间之间的天数
首先先把字符串转换成date类型
1 public static Date stringToDate(String dateStr, String formatStr) { 2 DateFormat sdf = new SimpleDateFormat(formatStr); 3 Date date = null; 4 try { 5 date = sdf.parse(dateStr); 6 } catch (ParseException e) { 7 e.printStackTrace(); 8 } 9 return date; 10 }
输入起始日期和结束日期,
public static List<String> getDayList(String starDate, String endDate) { String dateFormat = "yyyyMMdd"; SimpleDateFormat format = new SimpleDateFormat(dateFormat); List<String> dayList = new ArrayList<String>(); //初始时间和结束时间相等,添加初始时间到list中(添加谁都一样) if (starDate.equals(endDate)) { dayList.add(starDate); } else if (starDate.compareTo(endDate) < 0) { //如果初始时间小于终止时间 while (starDate.compareTo(endDate) <= 0) { //放入初始时间 dayList.add(starDate); try { //算出初始时间和1970的时间差 long l = stringToDate(starDate, "yyyyMMdd").getTime(); //时间差减去一天的毫秒数,再转换成日期格式,即是第二天 starDate = format.format(l + 3600 * 24 * 1000); } catch (Exception e) { e.printStackTrace(); } } } else { //初始时间大于结束时间 System.err.println("begin>end"); while (endDate.compareTo(starDate)<=0) { dayList.add(endDate); try { long l2=stringToDate(endDate, "yyyyMMdd").getTime(); endDate=format.format(l2+3600*24*1000); } catch (Exception e) { // TODO: handle exception System.err.println(e.getMessage()); } } } // Collections.reverse(dayList);//倒序 return dayList; }
调用函数:
1 public static void main(String[] args) 2 { 3 DayList dayList=new DayList(); 4 List daylists=dayList.getDayList("20171231", "20170501"); 5 Iterator<String> listsIterator=daylists.iterator(); 6 while (listsIterator.hasNext()) 7 { 8 System.err.println(listsIterator.next()); 9 10 } 11 12 }