简体   繁体   中英

How to get Alternate Dates between Two Dates in java?

In my Java Application i'm print all the Dates between Two dates by using below code..

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+"          ");
    }

But i Want 2 types of Date like....

  1. Getting alternative Day EX: 2012-12-01 2012-12-03 2012-12-06
  2. And i want Print only Saturday and Sunday in given two Dates.

Actually i'm trying to Print i+1 or i-1 it gives Array Index out of Bound..

I think you can try in this way -

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());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM