我试图像这样得到一周中的当前一周和一周的一周: 像这样声明我的变量:
Calendar calWeek;
Calendar calDay;
设置如下值:
calWeek = Calendar.getInstance();
calWeek.setFirstDayOfWeek(Calendar.MONDAY);
calWeek.set(Calendar.WEEK_OF_YEAR, Calendar.MONDAY);
calDay = Calendar.getInstance();
calDay.setFirstDayOfWeek(Calendar.MONDAY);
calDay.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int currentWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
int dayInWeek = calDay.get(Calendar.DAY_OF_WEEK);
currentWeek
返回2,dayInWeek
返回2.当前周为1,周三为止。 (一周的第3天)
即使我在设备上更改日期,输出也相同,currentWeek
返回2,dayInWeek
返回2.
为什么它总是返回相同的日期?
祝你好运, Dridia
答案 0 :(得分:2)
如Mike M的评论所述:您将两个值都设置为Calendar.MONDAY
,等于2
。
Calendar.getInstance()
会返回一个包含当前日期的实例,但如果您拨打calendarInstance.get(Calendar.WEEK_OF_YEAR)
,则仍会获得2,因为根据文档:
设置或获取WEEK_OF_MONTH或WEEK_OF_YEAR字段时,日历必须将月份或年份的第一周确定为参考点。 一个月或一年的第一周被定义为从getFirstDayOfWeek()开始并且包含该月或年的getMinimalDaysInFirstWeek()天的最早的七天....
我刚刚尝试过,getMinimalDaysInFirstWeek()
默认返回1
。所以你应该把它设置为7
天。所以第一周将在周一开始,如你所料。
一个Calendar实例已足够,您的代码应如下所示:
Calendar calendarInstance = Calendar.getInstance();
calendarInstance.setFirstDayOfWeek(Calendar.MONDAY);
calendarInstance.setMinimalDaysInFirstWeek(7);
int currentWeek = calendarInstance.get(Calendar.WEEK_OF_YEAR);
int dayInWeek = calendarInstance.get(Calendar.DAY_OF_WEEK);
System.out.println("week = " + currentWeek);
System.out.println("day of week = " + dayInWeek);
打印:
week = 1
day of week = 4
P.S。 4表示星期三