如何获得两个日期之间的日期的名单? [英] How to get list of dates between two dates?

查看:118
本文介绍了如何获得两个日期之间的日期的名单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,用户应选择日期从列表视图。问题是产生该列表。比如我需要的所有日期的 2010-2013 六月至八月(期间可能的 ,< STRONG>年)。是否有允许获取数据的方法?

In my application user should select date from listview. The problem is generating this list. For example I need all dates between 2010-2013 or June-August (period maybe day, month, year). Is there any method that allows to get that data?

例: 我需要之间的 2013年1月1日的日期 - 2013年1月10日

  1. 在2013年1月1日
  2. 在2013年1月2日
  3. 在2013年1月3日
  4. 在2013年4月1日
  5. 在2013年1月5号
  6. 在2013年1月6日
  7. 在2013年7月1日
  8. 在2013年1月8日
  9. 在2013年9月1号
  10. 在2013年10月1日
  1. 01.01.2013
  2. 02.01.2013
  3. 03.01.2013
  4. 04.01.2013
  5. 05.01.2013
  6. 06.01.2013
  7. 07.01.2013
  8. 08.01.2013
  9. 09.01.2013
  10. 10.01.2013

在此先感谢

推荐答案

对于列表的,你可能只是做:

For a list you could just do:

public static List<LocalDate> datesBetween(LocalDate start, LocalDate end) {
    List<LocalDate> ret = new ArrayList<LocalDate>();
    for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
        ret.add(date);
    }
    return ret;
}

请注意,这将包括结束。如果你想让它的不包括的结束,只是在循环中的条件更改为 date.isBefore(完)

Note, that will include end. If you want it to exclude the end, just change the condition in the loop to date.isBefore(end).

如果你只需要一个可迭代&LT; LocalDate&GT; 您可以编写自己的类来做到这一点非常有效的,而不是建立一个列表。你可以使用匿名类做到这一点,如果你不介意嵌套的公平程度。例如(未经测试):

If you only need an Iterable<LocalDate> you could write your own class to do this very efficiently rather than building up a list. You could do this with an anonymous class, if you didn't mind a fair degree of nesting. For example (untested):

public static Iterable<LocalDate> datesBetween(final LocalDate start,
                                               final LocalDate end) {
    return new Iterable<LocalDate>() {
        @Override public Iterator<LocalDate> iterator() {
            return new Iterator<LocalDate>() {
                private LocalDate next = start;

                @Override
                public boolean hasNext() {
                    return !next.isAfter(end);
                }

                @Override
                public LocalDate next() {
                    if (next.isAfter(end)) {
                        throw NoSuchElementException();
                    }
                    LocalDate ret = next;
                    next = next.plusDays(1);
                    return ret;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    };
}

这篇关于如何获得两个日期之间的日期的名单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆