在我的应用程序中,用户应该从listview
中选择date。问题是生成这个列表。例如,我需要2010-2013年或6-8月之间的所有日期(可能是day、month、年份E 210
)。有什么方法允许获取数据吗?
示例:我需要在01.01.2013-10.01.2013之间的日期
提前感谢
发布于 2013-07-17 06:27:06
对于一个清单,你只需做:
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;
}
注意,这将包括end
。如果希望它排除结束,只需将循环中的条件更改为date.isBefore(end)
即可。
如果您只需要一个Iterable<LocalDate>
,那么您可以编写自己的类来非常有效地完成这个任务,而不是构建一个列表。如果你不介意有一定程度的嵌套,你可以用一个匿名类来做这件事。例如(未经测试):
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();
}
};
}
};
}
发布于 2013-07-17 06:35:27
使用这样的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<Date> dateInterval(Date initial, Date final) {
List<Date> dates = new ArrayList<Date>();
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;
}
干杯!
学分:this
https://stackoverflow.com/questions/17692575
复制相似问题