我在我的 Android 项目中需要做的是找到过去三个月的所有前周二,并将它们放入一个字符串数组中。看来,Calendar Class
也不SimpleDateFormat
适用于此。
例如,今天是星期二,所以它从今天开始,我需要返回 2013_8_13,数组中的下一个是 2013_8_6,然后是 2013_7_30,依此类推。我错了吗Calendar Class
or SimpleDateFormat
?如果是这样,你能给我一个关于如何完成的想法吗?
编辑:更新答案回到某一天而不是回到某一天。还将 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++;
}