简体   繁体   English

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

[英]printing dates between two different dates in Java

I am trying to get dates between given two dates and days, for example 我正在尝试获取给定两个日期和日期之间的日期,例如

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

between these dates I am supposed to print dates between Monday to Friday for example. 在这些日期之间,例如,我应该打印星期一至星期五之间的日期。 here is the code I developed: 这是我开发的代码:

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

}

What I am supposed to see is: 我应该看到的是:

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)

but what I am getting is: 但是我得到的是:

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

A few issues 一些问题

  • You're reusing the same DateFormat uses to parse the input data String which is missing the required day ( E ) pattern. 您将重复使用相同的DateFormat来解析缺少所需的日( E )模式的输入数据String Create a separate SimpleDateFormat with pattern dd/MM/yyyy (EEEE) to display the output. 用模式dd/MM/yyyy (EEEE)创建一个单独的SimpleDateFormat以显示输出。
  • There is only output if the day is Monday or Friday, whereas there should only be output for a weekend day. 仅当一天是星期一或星期五时才输出,而只有周末时才输出。
  • Displaying the output for variable cal1 is unnecessary 不需要显示变量cal1的输出

Example: 例:

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

You can use EEEE to print day name.. 您可以使用EEEE打印日期名称。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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