簡體   English   中英

如何在Java中獲取兩個日期之間的替代日期?

[英]How to get Alternate Dates between Two Dates in java?

在我的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. 我想在給定的兩個日期中僅打印星期六和星期日。

實際上我正在嘗試打印i+1 or i-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());

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM