获取日期范围内的日期数组

时间:2018-09-19 08:08:15

标签: android arrays for-loop

如何通过循环将日期之间的日期存储到数组中的日期?

示例1:
第一次约会= 26/9/2018
最后日期= 30/9/2018

我想按如下所示循环存储日期:

new Date["26/9/2018","27/9/2018","28/9/2018","29/9/2018","30/9/2018"]

类似的东西:

for(int i = 0; FirstDate < LastDate; i++){
   //add array here by loop
}

当我选择以下内容时,我得到了new Date[4]

new Date[3],它将显示29/9/2018

3 个答案:

答案 0 :(得分:1)

I suggest you to use LocalDate api by Jake Warthon. Date api is not very reliable in android. By the way, try this solution:

public ArrayList<LocalDate> getDateLoop() {
        LocalDate startDate = LocalDate.of(2018, 9, 26);
        LocalDate endDate = LocalDate.of(2018, 9, 30);
        ArrayList<LocalDate> dates = new ArrayList<>();

        for (int i = startDate.getDayOfMonth(); i <= endDate.getDayOfMonth(); i++) {
            LocalDate dateToAdd = LocalDate.of(startDate.getYear(), startDate.getMonth(), i);
            dates.add(dateToAdd);
        }
        return dates;
    }

Here it is library's link: https://github.com/JakeWharton/ThreeTenABP

答案 1 :(得分:0)

您可以尝试以下方法:

        List<Date> dates = new ArrayList<Date>();

        String start_date ="26/9/2018";
        String end_date ="30/9/2018";

        DateFormat formatter ;

        formatter = new SimpleDateFormat("dd/M/yyyy");
        Date  startDate = null;
        Date  endDate = null;
        try {
            startDate = formatter.parse(start_date);
            endDate = formatter.parse(end_date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        long interval = 24*1000 * 60 * 60;
        long endTime =endDate.getTime() ;
        long curTime = startDate.getTime();
        while (curTime <= endTime) {
            dates.add(new Date(curTime));
            curTime += interval;
        }
        for(int i=0;i<dates.size();i++){
            String result = formatter.format(dates.get(i));
        }

可能不是最佳选择,但测试成功,希望对您有所帮助。

答案 2 :(得分:0)

只需使用以下代码:

public Date[] getDateLoop() {
  String str_start_date = "26/9/2018";
  String str_end_date = "30/9/2018";
  SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
  //Date date = sdf.parse(dateStr);
  Date start_date = null;
  try {
      start_date = sdf.parse(str_start_date);
  } catch (ParseException e) {
      e.printStackTrace();
  }

  Date end_date = null;
  try {
      end_date = sdf.parse(str_end_date);
  } catch (ParseException e) {
      e.printStackTrace();
  }

  long diff = TimeUnit.DAYS.convert(end_date.getTime() - start_date.getTime(), TimeUnit.MILLISECONDS);

  Date[] array_date = new Date[(int) diff + 1];
  for (int i = 0; i <= diff; i++) {
      Date temp_date = start_date;
      Calendar c = Calendar.getInstance();
      c.setTime(temp_date);
      c.add(Calendar.DATE, i);
      temp_date = c.getTime();
      array_date[i] = temp_date;
  }
  return array_date;
}