如何在java中的两个日期之间获得备用日期?

时间:2012-12-04 09:35:14

标签: java date datetime

在我的Java应用程序中,我使用下面的代码打印两个日期之间的所有日期..

List<Date> dates = new ArrayList<Date>();

    String str_date ="2012-12-01";
    String end_date ="2012-12-06";

    DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
    Date  startDate = (Date)formatter.parse(str_date); 
    Date  endDate = (Date)formatter.parse(end_date);
    long interval = 24*1000 * 60 * 60; // 1 hour in millis
    long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
    long curTime = startDate.getTime();
    while (curTime <= endTime) {
        dates.add(new Date(curTime));
        curTime += interval;
    }
    int i=0;
    for(i=0+i;i<dates.size();i++){
        Date d =(Date)dates.get(i);
        String ds = formatter.format(d);    
        System.out.println("             " + ds+"          ");
    }

但是我想要2种类型的日期......

  1. 获取替代日EX:2012-12-01 2012-12-03 2012-12-06
  2. 我希望在给定的两个日期内仅在周六和周日打印。
  3. 实际上我正在尝试打印i+1 or i-1它会让阵列索引超出界限..

1 个答案:

答案 0 :(得分:1)

我认为你可以这样试试 -

Date startDate = (Date) formatter.parse(str_date);
Date endDate = (Date) formatter.parse(end_date);

Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
cal.setTime(startDate);
cal1.setTime(endDate);
int i=0; // use this for alternative date print
while (!cal.equals(cal1)) {
    cal.add(Calendar.DATE, 1);
    if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
         System.out.println(cal.get(Calendar.DAY_OF_WEEK)); 
    System.out.println(cal.getTime());

}