返回了错误的week_of_month和day_of_month

时间:2016-12-17 17:42:11

标签: android gregorian-calendar

这是我的代码:

Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.WEEK_OF_YEAR, selectedWeek);
c.set(Calendar.YEAR, selectedYear);

Log.v(FILE_NAME,"C content: " + c.toString());

int firstDayOfWeek = c.getFirstDayOfWeek();
String[] days = new String[firstDayOfWeek + 7];

for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
    c.set(Calendar.DAY_OF_WEEK, i);
    days[i] = new SimpleDateFormat("d MMM").format(c.getTime());             
}

Log.v(FILE_NAME, "Start " + days[firstDayOfWeek] + " to " + days[firstDayOfWeek + 6]);

我将selectedWeek设置为51,selectYear到2016.所以我的期望是,因为我已经给了一周和一年,在我的上一个Log.v中,我应该得到给定周的日期列表(51),这是12月19日至12月25日。相反,我总是得到当周的日期(例如,目前我将永远在12月12日至12月18日)

显示c的内容给我

java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Asia/Kuala_Lumpur,firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=11,WEEK_OF_YEAR=52,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=353,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=1,HOUR_OF_DAY=1,MINUTE=24,SECOND=46,MILLISECOND=30,ZONE_OFFSET=28800000,DST_OFFSET=0]

似乎WEEK_OF_MONTH返回CURRENT WEEK_OF_MONTH,而不是给定的selectedWeek和selectedYear。 DAY_OF_MONTH也是如此。我的假设是DAY_OF_MONTH至少应该返回给定selectedWeek的开始日期?

我错误地理解了吗?如果我这样做了,那么我应该怎么做呢[firstDayOfWeek]返回给定的一周和一年的第一天?

1 个答案:

答案 0 :(得分:1)

我想我弄明白了这个问题。问题是,当您设置Calendar.DAY_OF_WEEK时,日历会自行重置,只需将星期几更改为您设置的日期。 因此,为了使代码有效,您必须在for循环中设置Calendar.WEEK_OF_YEAR

for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
            c.set(Calendar.DAY_OF_WEEK, i);
            c.set(Calendar.WEEK_OF_YEAR, selectedWeek);
            days[i] = new SimpleDateFormat("d MMM").format(c.getTime());
        }