如何获取两个日期之间的日期列表?
在我的应用程序中,用户应从listview
选择日期。 问题是生成此列表。 例如,我需要2010-2013或6月至8月之间的所有日期(期间可能是日 , 月 , 年 )。 是否有任何方法可以获取该数据?
示例:我需要在2013年1月1日至2013年10月1日之间的日期
- 2013年1月1日
- 2013年2月1日
- 2013年3月1日
- 2013年4月1日
- 2013年5月1日
- 2013年6月1日
- 2013年7月1日
- 2013年8月1日
- 2013年9月1日
- 2013年1月10日
提前致谢
对于列表,您可以这样做:
public static List datesBetween(LocalDate start, LocalDate end) { List ret = new ArrayList (); for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) { ret.add(date); } return ret; }
注意,这将包括end
。 如果您希望它排除结束,只需将循环中的条件更改为date.isBefore(end)
。
如果您只需要一个Iterable
您可以编写自己的类来非常有效地执行此操作,而不是构建列表。 如果您不介意相当程度的嵌套,您可以使用匿名类来完成此操作。 例如(未经测试):
public static Iterable datesBetween(final LocalDate start, final LocalDate end) { return new Iterable () { @Override public Iterator iterator() { return new Iterator () { 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(); } }; } }; }
像这样使用DatePicker
片段:
private static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // Copy the Date to the EditText set. dateValue = String.format("%04d", year) + "-" + String.format("%02d", monthOfYear + 1) + "-" + String.format("%02d", dayOfMonth); } }
这应该更容易获得日期。 使用以下代码进行日期范围:
public static List dateInterval(Date initial, Date final) { List dates = new ArrayList (); Calendar calendar = Calendar.getInstance(); calendar.setTime(initial); while (calendar.getTime().before(final)) { Date result = calendar.getTime(); dates.add(result); calendar.add(Calendar.DATE, 1); } return dates; }
干杯!
致谢: 这个
创建开始日期,增加一天,循环结束日期之前。
有许多Stack Overflowpost可以告诉你如何“添加一天到目前为止”。
- 使用JSON数据绘制线图,Android
- 解析数据时出错org.json.JSONException:java.lang.String类型的值<br无法转换为JSONObject
- 将PlayN游戏嵌入到Android活动中
- 如何通过蓝牙连接两个设备通过参数发送配对代码? JAVA,Android的
- java.net.ConnectException:连接拒绝TCP
- java.lang.OutOfMemoryError:无法分配带有16777216个空闲字节的571401228字节分配和直到OOM的495MB
- Android中的字符串加密
- 在队列中记录语音并将其发送到服务器
- Android启动画面 – 来自SD卡的图像?