在Java中打印两个不同日期之间的日期

时间:2014-04-20 16:41:38

标签: java date

我正在尝试在给定的两个日期和日期之间获取日期,例如

日期范围20/04/2014 - 210/05/2015

在这些日期之间我应该打印星期一到星期五之间的日期。这是我开发的代码:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date startDate = (Date) formatter.parse("20/04/2014");
Date endDate = (Date) formatter.parse("10/05/2014");

Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();

cal.setTime(startDate);
cal1.setTime(endDate);

while (!cal.equals(cal1)) {
    cal.add(Calendar.DATE, 1);
    if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY|| cal1.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
        System.out.println(formatter.format(cal.getTime()));
        System.out.println(formatter.format(cal1.getTime()));
    }
    //System.out.println(formatter.format(cal.getTime()));

}

我应该看到的是:

21/04/2014(Monday)    
22/04/2014(Tuesday)    
23/04/2014(Wednesday)    
24/04/2014(Thursday)    
25/04/2014(Friday)    
28/04/2014(Monday)    
29/04/2014(Tuesday)    
30/04/2014(Wednesday)    
01/05/2014(Thursday)    
02/05/2014(Friday)    
05/05/2014(Monday)    
06/05/2014(Tuesday)    
07/05/2014(Wednesday)    
08/05/2014(Thursday)    
09/05/2014(Friday)

但我得到的是:

21/04/2014    
20/05/2014    
28/04/2014    
20/05/2014    
05/05/2014    
20/05/2014    
12/05/2014    
20/05/2014    
19/05/2014    
20/05/2014

2 个答案:

答案 0 :(得分:2)

一些问题

  • 您正在重复使用相同的DateFormat用于解析缺少所需日期(String)模式的输入数据E。使用模式SimpleDateFormat创建单独的dd/MM/yyyy (EEEE)以显示输出。
  • 如果当天是星期一或星期五,则只有输出,而周末只应输出。
  • 不需要显示变量cal1的输出

示例:

while (!calendar1.equals(calendar2)) {
    calendar1.add(Calendar.DATE, 1);
    if (!(calendar1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) &&
               !calendar2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)) {
        System.out.println(outputFormatter.format(calendar1.getTime()));
    }
}

答案 1 :(得分:2)

您可以使用EEEE打印日期名称..

formatter = new SimpleDateFormat("dd/MM/yyyy(EEEE)");
System.out.println(formatter.format(cal.getTime()));