查找给定范围内的所有上周二?

时间:2013-08-13 15:28:41

标签: java android

我在Android项目中需要做的是查找过去三个月的所有上周二,并将它们放入String Array中。似乎Calendar ClassSimpleDateFormat都不适用于此。

例如,今天是星期二,所以它将从今天开始,我需要返回2013_8_13,阵列中的下一个将是2013_8_6,然后是2013_7_30,依此类推。我错了Calendar ClassSimpleDateFormat?如果是这样,你能否告诉我如何做到这一点?

1 个答案:

答案 0 :(得分:1)

编辑:更新了答案,回到某一天,而不是回到特定天数。还将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++;
}