我在Android项目中需要做的是找到过去三个月中所有以前的星期二,并将它们放入字符串数组中。看来Calendar ClassSimpleDateFormat都不适合这个。

例如,今天是星期二,所以它将从今天开始,我需要返回2013_8_13,数组中的下一个是2013_8_6,然后是2013_7_30,依此类推。我在Calendar ClassSimpleDateFormat上错了吗?如果是这样,您能给我一个大概的想法吗?

最佳答案

编辑:更新了答案以返回到特定日期而不是返回特定天数。还将String数组更改为ArrayList

ArrayList<String> tuesdayArrayList = new ArrayList<String>();

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_M_d");

Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);

Date date = new Date();

Date cutoffDate;
int cutoffYear = 2013;
int cutoffMonth = Calendar.JUNE;
int cutoffDayOfMonth = 25;
cutoffDate = new GregorianCalendar(cutoffYear, cutoffMonth, cutoffDayOfMonth).getTime();

while (day != Calendar.TUESDAY) {
    calendar.add(Calendar.DATE, 1);
    day = calendar.get(Calendar.DAY_OF_WEEK);
}

int i = 0;
while (date.after(cutoffDate)) {
    calendar.add(Calendar.DATE, -7);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
    date = new GregorianCalendar(year, month, dayOfMonth).getTime();
    tuesdayArrayList.add(dateFormat.format(date));
    Log.d("myTag: ", tuesdayArrayList.get(i));
    i++;
}

关于java - 查找给定范围内的所有以前的星期二?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18213230/

10-10 10:14