如何在java中迭代开始日期到结束日期

如何在java中迭代开始日期到结束日期,java,Java,嗨,我需要找到java的中间日期,例如 起始日期=2017-01-28和 截止日期=2017-02-03 我预计产出: 2017-01-28 2017-01-29 2017-01-30 2017-01-31 2017-02-01 2017-02-02 2017-02-03 请帮我谢谢..您可以使用Java日历来实现这一点: Date start = new Date(); Date end = new Date(); Calendar cStart = Calendar.get

嗨,我需要找到java的中间日期,例如

起始日期=2017-01-28和

截止日期=2017-02-03

我预计产出:

2017-01-28 
2017-01-29 
2017-01-30 
2017-01-31 
2017-02-01 
2017-02-02 
2017-02-03 

请帮我谢谢..

您可以使用Java日历来实现这一点:

Date start = new Date();
Date end = new Date();

Calendar cStart = Calendar.getInstance(); cStart.setTime(start);
Calendar cEnd = Calendar.getInstance(); cEnd.setTime(end);

while (cStart.before(cEnd)) {

    //add one day to date
    cStart.add(Calendar.DAY_OF_MONTH, 1);

    //do something...
}

您可以使用Java日历来实现这一点:

Date start = new Date();
Date end = new Date();

Calendar cStart = Calendar.getInstance(); cStart.setTime(start);
Calendar cEnd = Calendar.getInstance(); cEnd.setTime(end);

while (cStart.before(cEnd)) {

    //add one day to date
    cStart.add(Calendar.DAY_OF_MONTH, 1);

    //do something...
}

嗯,你可以使用


我完全推荐使用Joda Time而不是内置的Date/Calendar类。

好吧,您可以使用


我完全建议在内置的日期/日历类上使用Joda Time。

使用Java.Time包在Java 8中回答


使用包Java.time在Java8中回答


您尝试了什么?我尝试了这种类型,但不适用于LocalDate=fromDate;date.isBeforeendDate;date=date.plusDays1{}N,它之前已经被多次询问,并以Stackoverflow.SimpleDateFormat=new SimpleDateFormatyyy-M-d回答;日期d1=空;日期d2=空;试试{d1=format.parsefromDate;d2=format.parseendDate;}catch ParseException e{e.printStackTrace;}问题也是如此;如何解析LocalDate,或者是如何将日期转换为LocalDate。您尝试了什么?我尝试了这种类型,但不适用于LocalDate=fromDate;date.isBeforeendDate;date=date.plusDays1{}N,它之前已经被多次询问,并以Stackoverflow.SimpleDateFormat=new SimpleDateFormatyyy-M-d回答;日期d1=空;日期d2=空;试试{d1=format.parsefromDate;d2=format.parseendDate;}catch ParseException e{e.printStackTrace;}问题也是如此;如何解析LocalDate,或者如何将日期转换为LocalDate。
StringBuilder builder = new StringBuilder();
LocalDate startDate = LocalDate.parse("2017-01-28");
LocalDate endDate = LocalDate.parse("2017-02-03");
LocalDate d = startDate;

while (d.isBefore(endDate) || d.equals(endDate)) {
  builder.append(d.format(DateTimeFormatter.ISO_DATE)).append(" ");
  d = d.plusDays(1);
}

// "2017-01-28 2017-01-29 2017-01-30 2017-01-31 2017-02-01 2017-02-02 2017-02-03"
String result = builder.toString().trim();