【问题标题】:How To iterate the Start Date to end Date in java [duplicate]如何在java中迭代开始日期到结束日期[重复]
【发布时间】:2017-02-20 09:58:56
【问题描述】:

您好,我需要找到 Java 的 In between Dates 示例

StartDate=2017-01-28

EndDate=2017-02-03

我期望输出:

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

请帮我谢谢你..

【问题讨论】:

  • 你尝试了什么?
  • 我尝试过这种类型但不适用于 (LocalDate date = fromDate; date.isBefore(endDate); date = date.plusDays(1)) { }
  • N,之前已经被问过很多次,在 Stackoverflow 中已经回答了。
  • SimpleDateFormat 格式 = new SimpleDateFormat("yyyy-M-d");日期 d1 = null;日期 d2 = null;尝试 { d1 = format.parse(fromDate); d2 = format.parse(endDate); } catch (ParseException e) { e.printStackTrace(); }
  • 问题也是如此;我如何解析LocalDate,还是如何将日期转换为LocalDate。

标签: java


【解决方案1】:

您可以使用 Java Calendar 来实现:

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...
}

【讨论】:

    【解决方案2】:

    使用包 java.time 在 Java 8 中回答。

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

    【讨论】:

      【解决方案3】:

      好吧,你可以这样做(使用Joda Time

      for (LocalDate date = startDate; date.isBefore(endDate); date =    date.plusDays(1))
      {
         ...
      }
      

      我强烈建议在内置日期/日历类上使用 Joda Time。

      【讨论】:

        猜你喜欢
        • 2013-03-13
        • 2018-04-12
        • 1970-01-01
        • 2011-03-07
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-02
        相关资源
        最近更新 更多